<?php
/********************* database functions ************************/
//linkto
function linkto($link){
	if(!empty($link)){
		header("location: {$link}");
		exit();
	}
}

function encrypt($str){
	return sha1(md5($str));
}

function array_insert($arr_1 = array(), $arr_data = array(), $key_search){
	$arr = array();
	foreach($arr_1 as $k => $v){
		if($k == $key_search){
			foreach($arr_data as $key => $val)
				$arr[$key] = $val;
		}
		$arr[$k] = $v;
	}
	return $arr;
}

function array_insert_at($arr_1 = array(), $data, $key = 0, $index = 0){
	$arr_2 = array($key => $data);
	return array_merge(array_slice($arr_1, 0, $index), $arr_2, array_slice($arr_1, $index));
}

//generate id from database
function generate_id($table_name, $column_id, $id_started){
	if(!empty($table_name) && !empty($column_id) && !empty($id_started)){
		$sql = "SELECT * FROM `$table_name` WHERE 1 ORDER BY `$column_id`  DESC LIMIT 1 ";
		$rs = mysql_query($sql);
		if(@mysql_num_rows($rs) > 0){
			$r =  mysql_fetch_array($rs);
			$id  = $r["$column_id"];
			$id_ended = ($id >= $id_started) ? $id + 1 : $id_started; 
			@mysql_free_result($rs);
		}else{
			$id_ended  = $id_started;
		}
		return $id_ended;
	}else{
		return "Please fill up table_name, column_id, id_started";
	}	
}
//echo generate_id ("m_category", "categoryID",  "10001");

//make single select option from database
function single_option($id = "", $option_name, $table_name, $where_cond = "", $column_name, $column_id, $onchange = "", $option_id = ""){	
	$where_cond = !empty($where_cond) ? $where_cond : "1";
	if(!empty($table_name) && !empty($option_name) && !empty($column_name) && !empty($column_id)){		
		$option = "<select name='{$option_name}' $option_id $onchange >\n\t<option value='' >Chọn giá trị</option>\n\t";
		$q1 = "select * from `$table_name` where $where_cond";
		$r1 = mysql_query($q1) or die(mysql_error());
		if(@mysql_num_rows($r1) > 0){
			while($a1 = @mysql_fetch_array($r1)){
				$columnName = $a1["$column_name"];
				$columnID = $a1["$column_id"];
				$selected = ($columnID == $id) ? "selected='selected'" : "";
				$option .= "<option value=\"$columnID\" $selected>$columnName</option>\n\t";
			}
		}
		@mysql_free_result($r1);
		$option .= "</select>\n";		
		return $option;
	}else{
		return "Please fill up table_name, option_name, column_name, column_id";
	}
}
//echo single_option("10001", "categoryID", "m_category", "",  "categoryName", "categoryID", "onclick=\"\"", "id");

function single_option_v2($id = "", $option_name, $table_name, $where_cond = "", $column_name, $column_id, $onchange = "", $option_id = ""){
	$where_cond = !empty($where_cond) ? $where_cond : "1";
	if(!empty($id))
		$where_cond = "`{$column_id}` = '$id' OR ({$where_cond})";
	if(!empty($table_name) && !empty($option_name) && !empty($column_name) && !empty($column_id)){		
		$option = "<select name='{$option_name}' $option_id $onchange >\n\t<option value='' >Chọn giá trị</option>\n\t";
		$q1 = "select * from `$table_name` where $where_cond";
		$r1 = mysql_query($q1) or die(mysql_error());
		if(@mysql_num_rows($r1) > 0){
			while($a1 = @mysql_fetch_array($r1)){
				$columnName = $a1["$column_name"];
				$columnID = $a1["$column_id"];
				$selected = ($columnID == $id) ? "selected='selected'" : "";
				$option .= "<option value=\"$columnID\" $selected>$columnName</option>\n\t";
			}
		}
		@mysql_free_result($r1);
		$option .= "</select>\n";		
		return $option;
	}else{
		return "Please fill up table_name, option_name, column_name, column_id";
	}
}

//make multiple select option from database
function multiple_option($arr_id = "", $option_name, $option_size = 5, $table_name, $where_cond = "", $column_name, $column_id){
	$where_cond = !empty($where_cond) ? $where_cond : "1";
	if(!empty($table_name) && !empty($option_name) && !empty($column_name) && !empty($column_id)){
		$option = "<select name='{$option_name}[]' multiple='multiple' size='$option_size'>\n\t";
		$q1 = "select * from `$table_name` where $where_cond";
		$r1 = mysql_query($q1) or die(mysql_error());
		if(@mysql_num_rows($r1) > 0){
			while($a1 = @mysql_fetch_array($r1)){
				$columnName = $a1["$column_name"];
				$columnID = $a1["$column_id"];
				$selected = (@in_array($columnID, $arr_id)) ? "selected='selected'" : "";
				$option .= "<option value=\"$columnID\" $selected>$columnName</option>\n\t";
			}
		}
		@mysql_free_result($r1);
		$option .= "</select>\n";
		return $option;
	}else{
		return "Please fill up table_name, option_name, column_name, column_id";
	}
}
//echo @multiple_option(array("10001", "10003"), "categoryID", "5" , "m_category", "visible = 'y'", "categoryName", "categoryID");

//make radio option from database
function db_radio($table_name, $column_id, $wherecond = "", $id, $column_name){
	$where_cond = !empty($where_cond) ? $where_cond : "1";
	if(!empty($table_name) && !empty($column_name)){
		$i = 0;
		$radio = "";
		$q1 = "select * from `$table_name` where $wherecond";
		$r1 = mysql_query($q1) or die(mysql_error());
		$count = @mysql_num_rows($r1);
		if($count > 0){
			while($a1 = @mysql_fetch_array($r1)){
				$col_id = $a1["$column_id"];
				$col_name = $a1["$column_name"];
				$check = ($col_id == $id) ? "checked='checked'" : "";
				$radio .= "<input name='{$column_id}' type='radio' value='$col_id' id='{$column_name}_$col_id' $check/><label for='{$column_name}_$col_id'>$col_name</label>";
				$radio .= ($i == $count -1) ? "" : " / ";
				$i++;
			}
		}
		@mysql_free_result($r1);
		return $radio;
	}else{
		return "Please fill up array_name, column_name";
	}
}

//make checkbox selection from database
function db_checkbox($arr_id = array(), $checkbox_name, $table_name, $where_cond = "", $column_name, $column_id){
	$where_cond = !empty($where_cond) ? $where_cond : "1";
	if(!empty($table_name) && !empty($checkbox_name) && !empty($column_name) && !empty($column_id)){		
		$i = 0;
		$checkbox = "";
		$q1 = "select * from `$table_name` where $where_cond";
		$r1 = mysql_query($q1) or die(mysql_error());
		$num = @mysql_num_rows($r1);
		if($num > 0){
			while($a1 = @mysql_fetch_array($r1)){
				$columnName = $a1["$column_name"];
				$columnID = $a1["$column_id"];
				$checked = (@in_array($columnID, $arr_id)) ? "checked='checked'" : "";
				$checkbox .= "<input name='{$checkbox_name}[]' type='checkbox' value='$columnID' id='{$checkbox_name}_{$columnID}' $checked/><label for='{$checkbox_name}_{$columnID}'>$columnName</label>";
				$checkbox .= ($i == $num - 1) ? "" : " / ";
				$i++;
			}
		}
		@mysql_free_result($r1);
		return $checkbox;
	}else{
		return "Please fill up table_name, checkbox_name, column_name, column_id";
	}
}
//echo db_checkbox(array("10005"), "categoryID", "mst_category", "visible = 'y'", "categoryName", "categoryID");

//display single select from database
function single_select($table_name, $column_name, $wherecond = ""){
	$where_cond = !empty($wherecond) ? $wherecond : "1";
	if(!empty($table_name) && !empty($column_name)){
		$name = '';
		$q1 = "select * from `$table_name` where $where_cond limit 1";
		$r1 = mysql_query($q1) or die(mysql_error());
		if(@mysql_num_rows($r1) > 0){
			$a1 = @mysql_fetch_array($r1);
			@$name.= $a1["$column_name"];
		}
		@mysql_free_result($r1);	
		return $name;
	}else{
		return "";
	}
}
//echo single_select("m_category", "categoryName", "`categoryID` = 10001");

//display single select from database
function single_select_v2($table_name, $column_name, $wherecond = ""){
	if(strpos(strtolower($table_name), " from ") !== false){
		if(!empty($column_name)){			
			$name = '';
			$q1 = $table_name . $wherecond;
			$r1 = mysql_query($q1) or die(mysql_error());
			if(@mysql_num_rows($r1) > 0){
				$a1 = @mysql_fetch_array($r1);
				@$name.= $a1["$column_name"];
			}
			@mysql_free_result($r1);	
			return $name;
		}else{
			return "";
		}
	}
	else{
		$where_cond = !empty($wherecond) ? $wherecond : "1";
		if(!empty($table_name) && !empty($column_name)){
			$name = '';
			$q1 = "select * from `$table_name` where $where_cond limit 1";
			$r1 = mysql_query($q1) or die(mysql_error());
			if(@mysql_num_rows($r1) > 0){
				$a1 = @mysql_fetch_array($r1);
				@$name.= $a1["$column_name"];
			}
			@mysql_free_result($r1);	
			return $name;
		}else{
			return "";
		}
	}
}
//echo single_select("m_category", "categoryName", "`categoryID` = 10001");


//display multiple select from database (possible for display value of checkbox and radio)
function multiple_select($table_name, $column_id, $arr_id, $column_name, $ordercond = ""){
	if(!empty($table_name) && !empty($column_name) && !empty($column_id) && !empty($arr_id)){
		$name = "";
		$i = 1;
		$count = count($arr_id);
		if(!empty($arr_id) && $count > 0){
			foreach ($arr_id as $v) {
				$q1 = "select * from `$table_name` where $column_id = '$v' $ordercond";
				$r1 = mysql_query($q1) or die(mysql_error());
				if(@mysql_num_rows($r1) > 0){
					$a1 = @mysql_fetch_array($r1);
					$name.= ($count > $i) ? $a1["$column_name"]."、 " : $a1["$column_name"];
				}
				$i++;
				@mysql_free_result($r1);
			}
		}
		return $name;
	}else{
		return "";
	}
}
//echo multiple_select("m_category", "categoryID", "array("1", "2")", "categoryName", "");

/********************* array setting functions ************************/
//make single select option menu from array setting
function array_single_option($array_name, $value = "", $column_name, $default = "Chọn giá trị"){
	if(!empty($array_name) && !empty($column_name)){
		$option = "<select name='$column_name'>";
		if(!empty($default))		
			$option .= "\n\t<option value=\"\">{$default}</option>";
		foreach ($array_name as $k => $v) {
			$selected = ($value == $k) ? "selected='selected'" : "";
			$option .= "\n\t<option value=\"{$k}\" {$selected}>{$v}</option>";
		}
		$option .= "\n</select>";
		return $option;
	}else{
		return "Please fill up array_name, column_name";
	}
}
//echo array_single_option(array("s" => "1", "a" => "2"), "a", "delivery_state");

//make single select option menu from array setting
function array_single_option_v2($array_name, $value = "", $column_name, $extra = ""){
	if(!empty($array_name) && !empty($column_name)){
		$option = "<select {$extra} name='$column_name' id='$column_name'>\n<option value=\"\">Chọn giá trị</option>\n\t";
		foreach ($array_name as $k => $v) {
			$selected = "";
			if($value == $k){
				$selected = "selected='selected'";	
				$option = str_replace("\n<option value=\"\">Chọn giá trị</option>\n\t", "", $option);
			}
			$option .= "<option value=\"{$k}\" {$selected}>{$v}</option>\n\t";			
		}
		$option .= "</select>";		
		return $option;
	}else{
		return "Please fill up array_name, column_name";
	}
}
//echo array_single_option(array("s" => "1", "a" => "2"), "a", "delivery_state");

//display radio option from array setting
function array_radio($array_name, $value = "", $column_name){
	if(!empty($array_name) && !empty($column_name)){
		$i = 0;
		$count = count($array_name);
		$radio = "";
		foreach ($array_name as $k => $v) {
			$check = ($value == $k) ? "checked='checked'": "";
			$radio .= "<input name='{$column_name}' type='radio' value='$k' id='{$column_name}_$k' $check/><label for='{$column_name}_$k'>$v</label>";
			$radio .= ($i == $count -1) ? "" : " / ";
			$i++;
		}
		return $radio;
	}else{
		return "Please fill up array_name, column_name";
	}
}
//echo array_radio(array("s" => "1", "a" => "2"), "a", "delivery_state");

//checkbox selection from array setting
function array_checkbox($array_name, $checkbox_name, $array_value = array()){
	if(!empty($array_name) && !empty($checkbox_name)){
		$i = 0;
		$count = count($array_name);
		$checkbox = "";
		foreach ($array_name as $k => $v) {
			$check = @in_array($k, $array_value) ? "checked='checked'" : "";
			$checkbox .= "<input name='{$checkbox_name}[]' type='checkbox' value='$k' id='{$checkbox_name}_$k' $check/><label for='{$checkbox_name}_$k'>$v</label>";
			$checkbox .= ($i == $count -1) ? "" : " / ";
			$i++;
		}
		return $checkbox;
	}else{
		return "Please fill up array_name, checkbox_name";
	}
}
//echo array_checkbox(array("s" => "1", "a" => "2"), "memberType", array("s"));

//display single select from array setting
function array_single_select($array_name, $value = ""){
	if(!empty($array_name)){
		$name = "";
		foreach ($array_name as $k => $v) {
			if ($value == $k) {
				$name = $v;
				break;
			}
		}
		return $name;
	}else{
		return "Please fill up array_name";
	}
}
//echo array_single_select(array("s" => "1", "a" => "2"), "a");

//display multiple value from array setting (possible for display value of checkbox and radio and to view all array value)
function array_multiple_select($array_name, $array_value = array()){
	if(!empty($array_name)){
		$i = 0;
		$count = count($array_value);
		$name = "";
		foreach ($array_value as $value) {
			foreach ($array_name as $k => $v) {
				$name .= ($value == $k) ? $v : "";
			}
			$name .= ($i == $count -1) ? "" : "、 ";
			$i++;
		}
		return $name;
	}else{
		return "Please fill up array_name";
	}
}
//echo array_multiple_select(array("s" => "1", "a" => "2"), array("1", "2"));

//convert from array to string to insert or update the database
function array_to_string($array_name){
	$str = "";
	if(!empty($array_name) && @is_array($array_name)){
		$i = 0;
		$count  = count($array_name);
		foreach ($array_name as $k => $v) {
			$str .= ($i == $count -1) ? $k : $k."|";
			$i++;
		}
	}
	return $str;
}
//echo array_to_string(array("1", "2"));

/********************* Other functions ************************/
//number_format
function format_number($value){
	$str = 0;
	if(!empty($value)){
		$str = number_format($value, 0, ".", ",");
	}
	return $str;
}
// echo format_number("200000");

function format_number_excel($value){
	$str = 0;
	if(!empty($value)){
		$str = number_format($value, 1, ".", "");
	}
	return $str;
}

//select datetime
function datetime_option($option_name, $min_value, $max_value, $value_selected = "") {
	$option = "<select class='small' name='{$option_name}'>\n\t<option value=''>Chọn giá trị</option>\n\t";
	for($i = $min_value; $i <= $max_value; $i++){
		$stri = ($i < 10) ? "0".$i : $i;
		$selected = ($stri == $value_selected) ? "selected='selected'" : "";
		$option .= "<option value='$stri' $selected>$stri</option>\n\t";
	}
	$option .= "</select>";
	return $option;
}
//echo datetime_option("datetime", 00, 23, 12);

//select datetime
function datetime_option_v2($option_name, $min_value, $max_value, $value_selected = "", $text = "") {
	$option = "<select class='small' name='{$option_name}'>\n\t<option value=''>Chọn giá trị</option>\n\t";
	for($i = $min_value; $i <= $max_value; $i++){
		$stri = ($i < 10) ? "0".$i : $i;
		$selected = ($stri == $value_selected) ? "selected='selected'" : "";
		$option .= "<option value='$stri' $selected>$stri {$text}</option>\n\t";
	}
	$option .= "</select>";
	return $option;
}
//echo datetime_option("datetime", 00, 23, 12);

//upload image
function upload_image($var_name, $upload_path, $image_name, $maxx = 0, $maxy = 0){
	if(!empty($var_name) && !empty($image_name) && !empty($upload_path)){
		$image = !empty($_FILES[$var_name]['name']) ? $_FILES[$var_name]['name'] : "";
		if(!empty($image)){
			$imageExt = strtolower(substr($image, strrpos($image, '.'), strlen($image)));
			$image = $image_name.$imageExt;
			$uploadFile = $upload_path . "/" . $image;

			@unlink($upload_path."/".$_SESSION["$var_name"]);
			@copy($_FILES[$var_name]['tmp_name'], $uploadFile);			

			$_SESSION["$var_name"] = $image;
			
			if($maxx > 0 and $maxy > 0){
				crop($uploadFile, $uploadFile, $maxx, $maxy);			
			}
		}else{
			$image = !empty($_SESSION["$var_name"]) ? $_SESSION["$var_name"] : "";
		}
	}else{
		return "Please fill up variable, image name, upload path";
	}
}
//echo upload_image("categoryImage", $category_path, "category_", 0, 0);

//resize image
function crop($path_src, $path_desc, $thumb_width, $thumb_height){
	$PathImgOld = $path_src;
	$PathImgNew = $path_desc;
	$NewWidth = $thumb_width;	
	$NewHeight = $thumb_height;
	
	@list( $w, $h, $source_image_type ) = @getimagesize( $PathImgOld );
	if(empty($NewHeight))
		$NewHeight = intval($NewWidth * $h / $w);
		
	//$NewWidth=($NewWidth<$w)?$NewWidth:$w;
	//$NewHeight=($NewHeight<$h)?$NewHeight:$h;

	switch ( $source_image_type )
	{
		case IMAGETYPE_GIF:
			$simg = @imagecreatefromgif( $PathImgOld );
		break;
		
		case IMAGETYPE_JPEG:
			$simg = @imagecreatefromjpeg( $PathImgOld );
		break;
		
		case IMAGETYPE_PNG:
			$simg = @imagecreatefrompng( $PathImgOld );
	
		break;
	}

	$dimg = @imagecreatetruecolor($NewWidth, $NewHeight);
	@$wm = $w/$NewWidth;
	@$hm = $h/$NewHeight;
	$h_height = $NewHeight/2;
	$w_height = $NewWidth/2;
	if($w> $h) {
		@$adjusted_width = $w / $hm;
		$half_width = $adjusted_width / 2;
		$int_width = $half_width - $w_height;
		$imagecopyresampled=1;
		//imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$NewHeight,$w,$h);
	} elseif(($w <$h) || ($w == $h)) {
		@$adjusted_height = $h / $wm;
		$half_height = $adjusted_height / 2;
		$int_height = $half_height - $h_height;
		$imagecopyresampled=2;
		//imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$NewWidth,$adjusted_height,$w,$h);
	} else {
		$imagecopyresampled=3;
		//imagecopyresampled($dimg,$simg,0,0,0,0,$NewWidth,$NewHeight,$w,$h);
	}
	
	switch ( $source_image_type )
	{
		case IMAGETYPE_GIF:
			$colorTransparent = @imagecolortransparent($simg);
			@imagepalettecopy($dimg, $dimg);
		   	@imagefill($dimg, 0, 0, $colorTransparent);
		   	@imagecolortransparent($dimg, $colorTransparent);
		   	switch ($imagecopyresampled){
		   		case 1:
		   			@imagecopyresized($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$NewHeight,$w,$h);
		   			break;
		   		case 2:
		   			@imagecopyresized($dimg,$simg,0,-$int_height,0,0,$NewWidth,$adjusted_height,$w,$h);
		   			break;
		   		case 3:
		   			@imagecopyresized($dimg,$simg,0,0,0,0,$NewWidth,$NewHeight,$w,$h);
		   			break;	
		   	}
		   	//imagecopyresized($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
			@imagejpeg( $dimg, $PathImgNew, 90 );
		break;
		
		case IMAGETYPE_JPEG:
		    $colorTransparent = @imagecolortransparent($simg);
			@imagepalettecopy($dimg, $dimg);
		   	@imagefill($dimg, 0, 0, $colorTransparent);
		   	@imagecolortransparent($dimg, $colorTransparent);
			switch ($imagecopyresampled){
		   		case 1:
		   			@imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$NewHeight,$w,$h);
		   			break;
		   		case 2:
		   			@imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$NewWidth,$adjusted_height,$w,$h);
		   			break;
		   		case 3:
		   			@imagecopyresampled($dimg,$simg,0,0,0,0,$NewWidth,$NewHeight,$w,$h);
		   			break;	
		   	}
			//imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height );
			@imagejpeg( $dimg, $PathImgNew, 90 );
		break;
		
		case IMAGETYPE_PNG:
			$colorTransparent = @imagecolortransparent($simg);
			@imagepalettecopy($dimg, $dimg);
		   	@imagefill($dimg, 0, 0, $colorTransparent);
		   	@imagecolortransparent($dimg, $colorTransparent);
			switch ($imagecopyresampled){
		   		case 1:
		   			@imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$NewHeight,$w,$h);
		   			break;
		   		case 2:
		   			@imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$NewWidth,$adjusted_height,$w,$h);
		   			break;
		   		case 3:
		   			@imagecopyresampled($dimg,$simg,0,0,0,0,$NewWidth,$NewHeight,$w,$h);
		   			break;	
		   	}
			//imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height );
			@imagejpeg( $dimg, $PathImgNew, 90 );
		break;
	}
	
	@imagedestroy($dimg);
}

//view image
function view_image($image_path, $image_name, $image_dir = "", $height = "", $width = ""){
	$image_view = "";
	$height = (!empty($height)) ? "height = {$height}": "";
	$width = (!empty($width)) ? "width = {$width}": "";
	if(!empty($image_name)){
		$file = $image_path . $image_name;
		if(empty($image_dir))
			$image_dir = $image_path;			
		if(file_exists($image_dir . $image_name)){
			$image_view .= "<img src='$file?".date("YmdHis")."' $width $height />";
		}
	}
	return $image_view;
}
//echo view_image("../common/upload_img/banner_common/", "banner_common_10000003.gif", "", "");

//generate password
function generate_password( $name_length ){
    global $base_vow, $base_cons, $base_digit, $base_sfx, $readability;

    if( !$base_vow )   $base_vow   = "aaaeeeiiiooouuuy";
    if( !$base_sfx )   $base_sfx   = "abcdefghijklmnnoppqrrrstuvwwwxxyyyz";
    if( !$base_cons )  $base_cons  = "bcdfghjklmnpqrstvwxyz";
    if( !$base_digit ) $base_digit = "123456789"; //$base_digit = "123456789()!@#$%^&*-+={}[]:;<>,.?/";
                       $base_alpha = $base_vow . $base_cons;
    if( !$readability ) $readability = 95;
    //echo "$readability \n";

    $vow_or_con = "CON";    // kind of flip between vows and cons...
    $once_digit = FALSE;    // at least one digit
    $once_upper = FALSE;    // at least one upper letter
    $retval = '';
    mt_srand((double)microtime()*1000000);

    // ========= Now create a password. ===========
    while( strlen( $retval ) < $name_length )
    {
        // +------------- for cons... ------------+
        if( $vow_or_con == "CON" )
        {
            //$retval .= substr($base_digit,mt_rand(0,strlen($base_digit)-1),1);
            $retval .= substr($base_cons,mt_rand(0,strlen($base_cons)-1),1);
            $vow_or_con = "VOW";
            continue;
        }
        // +------------- for vows... --------------+
        $vow_or_con = "CON";
        $number  = mt_rand(0,100);
        if( $number < $readability )
        // change this to '80' will make password more pronnounceable.
        // change this to '99' will make password highly pronnounceable.
        {
           $retval .= substr($base_digit,mt_rand(0,strlen($base_digit)-1),1);
           //$retval .= substr($base_vow,mt_rand(0,strlen($base_vow)-1),1);
        }

        if( strlen( $retval ) >= $name_length ) continue;

        $number  = mt_rand(0,100);
        if( $number < 30 )
        {
            //$retval .= substr($base_digit,mt_rand(0,strlen($base_digit)-1),1);
            $retval .= substr($base_sfx,mt_rand(0,strlen($base_sfx)-1),1);
        }
        elseif( $number < 40 )
        {
            //$retval .= substr($base_digit,mt_rand(0,strlen($base_digit)-1),1);
            $retval .= strtoupper( substr($base_sfx,mt_rand(0,strlen($base_sfx)-1),1) );
            $once_upper = TRUE;
        }
        elseif( $number < 70 )
        {
            $retval .= substr($base_digit,mt_rand(0,strlen($base_digit)-1),1);
            $once_digit = TRUE;
        }
    } // === end of making a password... NOT YET. ===

    $retval      = substr( $retval, 0, $name_length ); // this is not necessary...

    if( !$once_upper ) // make sure password has at least one upper case letter.
    {
        $retval = substr_replace( $retval,
            strtoupper( substr( $base_alpha, mt_rand( 0, strlen( $base_alpha ) - 1 ), 1) ),
            mt_rand( 0, strlen( $retval ) - 1 ),
            1);
    }
    if( !$once_digit ) // make sure password has at least one digit letter.
    {
        // a bug; the digit can overwrite the upperletter...
        $retval = substr_replace( $retval,
            substr( $base_digit, mt_rand( 0, strlen( $base_digit ) - 1 ), 1 ),
            mt_rand( 0, strlen( $retval ) - 2 ) + 1,
            1);
    }

    return $retval;
}

//generate_password(8);

//function remove folder recursively
function folderDelete($path) {
	if (is_dir($path)) {
		if (version_compare(PHP_VERSION, '5.0.0') < 0) {
		$entries = array();
			if ($handle = opendir($path)) {
				while (false !== ($file = readdir($handle))) $entries[] = $file;
					closedir($handle);
			}
		}else{
			$entries = scandir($path);
			if ($entries === false) $entries = array();
		}
		
		foreach ($entries as $entry) {
			if ($entry != '.' && $entry != '..') {
				folderDelete($path.'/'.$entry);
			}
		}
		return rmdir($path);
	}else{
		return unlink($path);
	}
}

//function copy folder recursively
function folderCopy($source, $dest, $overwrite = false){ 
    if(!is_dir($dest)) { 
        @mkdir($dest); 
    } 
    if($handle = opendir($source)){ 
        while(false !== ($file = readdir($handle))){ 
            if($file != '.' && $file != '..'){ 
                $path = $source . '/' . $file; 
                if(is_file($path)){ 
                    if(!is_file($dest . '/' . $file) || $overwrite) { 
                        @copy($path, $dest . '/' . $file); 
                    } 
                } else if (is_dir($path)) { 
                    @chmod($path,0777); 
                    if(!is_dir($dest . '/' . $file)) { 
                        @mkdir($dest . '/' . $file); 
                        folderCopy($path, $dest . '/' . $file, $overwrite);//callback function - recursive 
                    } 
                    @chmod($path,0755); 
                } 
            } 
        } 
        closedir($handle); 
    } 
}  

function whereCond($table_name, $column_name, $return_name, $cond = "", $in_notin = ""){
	$arr_item = array();
	$sql = "SELECT `{$column_name}` FROM `{$table_name}` WHERE 1 {$cond}";
	$rs = mysql_query($sql);
	if(@mysql_num_rows($rs) > 0){
		while($row = @mysql_fetch_array($rs)){
			$itemID = $row["{$column_name}"];
			if(!empty($itemID)){
				$arr_itemID = explode("|", $itemID);
				foreach($arr_itemID as $value){
					if(@!in_array($value, $arr_item)){
						@array_push($arr_item, $value);
					}
				}
			}
		}
	}
	@mysql_free_result($rs);
	@sort($arr_item);
	$where_cond = "";
	$in_notin = (!empty($in_notin)) ? $in_notin : "IN";
	@$where_cond = implode("|", $arr_item);
	$where_cond = str_replace("|", "', '", $where_cond);
	$where_cond = " AND `{$return_name}` {$in_notin} ('{$where_cond}') ";
	
	return $where_cond;
}

//paging
function createPaging($url, $page, $number_of_items, $paging_value, $query_string){	
	$pgintf = "";
	$btn_top = "<<";
	$btn_prev = "<";
	$btn_next = ">";
	$btn_last = ">>";

	if(empty($page)){
		$page = 1;
	}
	
	$query_string = preg_replace("/[&]?page=" . $page ."/", "", $query_string);
	$query_string = (!empty($query_string) && strpos($query_string, "&") !== 0)  ? "&" . $query_string : $query_string;			
	
	$numofpage = ceil($number_of_items / $paging_value);

	if($page != 1){
		$bp = $page - 1;
		$pgintf .= "<a href='$url?page=1{$query_string}'>$btn_top</a> ";
		$pgintf .= "<a href='$url?page=$bp{$query_string}'>$btn_prev</a>";
	}else{
		$pgintf .= "$btn_top ";
		$pgintf .= "$btn_prev ";
	}

	$pgstart = $page - 2;
	if($pgstart < 1){
		$pgstart = 1;
	}
	$pgend = $pgstart + 9;
	if($pgend > $numofpage){
		$pgend = $numofpage;
		if($pgstart > 1){
			$pgstart = $pgend - 9;
			if($pgstart < 1){
				$pgstart = 1;
			}
		}
	}

	for($i=$pgstart;$i<=$pgend;$i++){
		if($i == $page){
			$pgintf .= $i;
		}else{
			$pgintf .= " <a href='$url?page=$i{$query_string}'>$i</a> ";
		}
	}

	if($page != $numofpage){
		$np = $page + 1;
		$pgintf .= " <a href='$url?page=$np{$query_string}'>$btn_next</a> ";
		$pgintf .= " <a href='$url?page=$numofpage{$query_string}'>$btn_last</a>";
	}else{
		$pgintf .= " $btn_next";
		$pgintf .= " $btn_last";
	}

	$startnum = $page * $paging_value - $paging_value;
	if($startnum < 0){
		$startnum = 0;
	}
	
	return array($pgintf, $startnum);
}

//list($pgintf, $startnum) = createPaging($_SERVER["PHP_SELF"], strip_tags(@$_GET["page"]), $num, $paging_value, $_SERVER["QUERY_STRING"]);

//display multiple select from database (possible for display value of checkbox and radio)
function multiple_select_v2($table_name, $column_id, $arr_id, $column_name, $ordercond = ""){
	$name = "";
	if(!empty($table_name) && !empty($column_name) && !empty($column_id) && !empty($arr_id)){
		$i = 1;
		$count = count($arr_id);
		if(!empty($arr_id) && $count > 0){
			$ids = implode(",", $arr_id);
			$q1 = "select * from `$table_name` where $column_id in ({$ids}) $ordercond";
			$r1 = mysql_query($q1) or die(mysql_error());
			$count = @mysql_num_rows($r1);
			if($count > 0){
				while($a1  = @mysql_fetch_array($r1)){				
					$name .= ($count > $i) ? $a1["$column_name"]."、 " : $a1["$column_name"];
					$i++;
				}
			}			
			@mysql_free_result($r1);
			
		}		
	}
	return $name;
}
//echo multiple_select("m_category", "categoryID", array("10001","10003"), "categoryName", "");

//some path function
function getPath($i = 0){
	$dir = dirname(dirname(__FILE__));
	$url = "";
	switch($i){
		case 0:
			$url = $dir . "/common/upload/gallery/";
			break;
		case 1:
			$url = $dir . "/admin/gallery_upload/server/php/files/";
			break;
		case 2:
			$url = $dir . "/admin/gallery_upload/server/php/thumbnails/";
			break;				
	}
	return $url;
}

function getLink($i = 0){
	/*$url = (isset($_SERVER['HTTPS']) ? 'http://' : 'http://').
    		(isset($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'' : '').
    		(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
    		(isset($_SERVER['HTTPS']) && $_SERVER['SERVER_PORT'] === 443 ||
    		$_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT'])));
	//$url .= substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
	/**/
	$url = "";
	switch($i){
		case 0:
			$url = $url . "/common/upload/photo/";
			break;
		case 1:
			$url = $url . "/admin/photo_upload/server/php/files/";
			break;
		case 2:
			$url = $url . "/admin/photo_upload/server/php/thumbnails/";
			break;			
	}
	return $url;
}

function copyAll($source,$destination){
	if (is_dir($source))
	{
		@mkdir( $destination );
		$directory = dir( $source );		
		while ( FALSE !== ( $readdirectory = $directory->read() ) )
		{
			if ( $readdirectory == '.' || $readdirectory == '..' )
			{
				continue;
			}
			$PathDir = $source . '/' . $readdirectory; 
			if ( is_dir( $PathDir ) ) 
			{
				copyAll( $PathDir, $destination . '/' . $readdirectory );
				continue;
			}
			@copy( $PathDir, $destination . '/' . $readdirectory );
		} 
		$directory->close();
	}
	else
	{
		@copy($source,$destination );
	}
}

function deleteAll($dirname){
	$dir_handle = "";
	if (is_dir($dirname))
      $dir_handle = opendir($dirname);
	if (!$dir_handle)
    	return;
	while($file = readdir($dir_handle)) {
		if ($file != "." && $file != "..") {
			if (!is_dir($dirname."/".$file))
				@unlink($dirname."/".$file);
			else
				deleteAll($dirname.'/'.$file);    
		}
	}
   closedir($dir_handle);   
   //@rmdir($dirname);
}

/* 2012-06-26 */

function check_array(&$array, $level)
{
	$kq = "";
	if(empty($array))
		$kq = "";
	else if(is_array($array)){
		$kq = $array[$level];
	}
	else
		$kq = $array;
	return $kq;
}

function createTreeCategory($tableName, $colID, $colName, $chkName, $arr_ids = array(array()), &$list, $tag = "div", $class = "", $where = "1", $order = "", $next_id, $ratio = "20", $level = 0)
{		
	if(!isset($tableName[$level]))
		return;
	$paddingLeft = $ratio * $level;
	$c_tableName = check_array($tableName, $level);
	$c_colID 	 = check_array($colID, $level);
	$c_colName	 = check_array($colName, $level);
	$c_chkName 	 = check_array($chkName, $level);	
	$c_where 	 = check_array($where, $level);
	$c_order 	 = check_array($order, $level);
	if(strrpos("select", $c_tableName))
		$sql = $c_tableName;
	else
		$sql = "select * from `{$c_tableName}`";
	
	if($level > 0){		
		if(is_array($c_colID)){			
			$c_where .= " AND " . $c_colID[1] . " = {$next_id}";
			$c_colID = $c_colID[0];
		}
		else
			$c_where .= $next_id;
	}
	
	$sql .= " where 1 {$c_where} {$c_order}";
	
	$c_class = check_array($class, $level);
	if(!empty($c_class)){
		$c_class = "class=\"{$c_class}\"";
	}	

	$rs = mysql_query($sql);
	if(@mysql_num_rows($rs) > 0){
		$id = "";
		if($level == 0)
			$id = " id=\"{$tag}_level{$level}\"";
		$list .= "<{$tag}{$id}>\n";
		while($row = mysql_fetch_array($rs)){
			$id 	= $row[$c_colID];
			$name 	= $row[$c_colName];
			$check = "";
			if(!empty($arr_ids[$level]))
				if(in_array($id, $arr_ids[$level]))
					$check = "checked=\"checked\"";
			switch($tag){
				case "div":
					$list .= "<div {$c_class} style=\"padding-left:{$paddingLeft}px;\">\n";
					$list .= "<span>\n\t<input name=\"{$c_chkName}[]\" id=\"{$c_chkName}_{$id}\" {$check} type=\"checkbox\" value=\"{$id}\">\n";
					$list .= "\t<label for=\"{$c_chkName}_{$id}\">{$name}</label>\n</span>\n";					
					createTreeCategory($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, $order, $id, $ratio, $level + 1);
					$list .= "</div>\n";					
					break;
				case "ul":
					$list .= "<li {$c_class} style=\"padding-left:{$paddingLeft}px;\">\n";
					$list .= "<span>\n\t<input name=\"{$c_chkName}[]\" id=\"{$c_chkName}_{$id}\" {$check} type=\"checkbox\" value=\"{$id}\">\n";
					$list .= "\t<label for=\"{$c_chkName}_{$id}\">{$name}</label>\n</span>\n";					
					createTreeCategory($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, $order, $id, $ratio, $level + 1);
					$list .= "</li>\n";					
					break;
				default:
					break;
			}			
		}//while($row = mysql_fetch_array($rs))
		$list .= "</{$tag}>\n";
	}//if(@mysql_num_rows($rs) > 0)
}

/*
$tableName 	= array("main_category", "mst_category", "sub_category");
$colID 		= array("mainCategoryID", array("categoryID", "mainCategoryID"), array("subCategoryID", "categoryID"));
$colName 	= array("mainCategoryNameVn", "categoryNameVn", "subCategoryNameVn");
$chkName 	= array("main_category", "mst_category", "sub_category");
$arr_ids 	= array(array("1001", "1002"), array("10001"), array("100003"));
$where 		= array(" AND `visible` = 'y'", " AND `visible` = 'y'", " AND `visible` = 'y'");
$tag 		= "ul";
$class		= array("main_category", "mst_category", "sub_category");
$order		= array("order by cast(`position` as signed) asc", "order by cast(`position` as signed) asc", "order by cast(`position` as signed) asc");

$list = "";
createTreeCategory($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, "", $order);
/**/

function createTreeCategoryView($tableName, $colID, $colName, $chkName, $arr_ids = array(array()), &$list, $tag = "div", $class = "", $where = "1", $order = "", $next_id, $ratio = "20", $level = 0)
{		
	if(!isset($tableName[$level]))
		return;
	$paddingLeft = $ratio * $level;
	$c_tableName = check_array($tableName, $level);
	$c_colID 	 = check_array($colID, $level);
	$c_colName	 = check_array($colName, $level);
	$c_chkName 	 = check_array($chkName, $level);	
	$c_where 	 = check_array($where, $level);
	$c_order 	 = check_array($order, $level);
	if(strrpos("select", $c_tableName))
		$sql = $c_tableName;
	else
		$sql = "select * from `{$c_tableName}`";
	
	if($level > 0){		
		if(is_array($c_colID)){			
			$c_where .= " AND " . $c_colID[1] . " = {$next_id}";
			$c_colID = $c_colID[0];
		}
		else
			$c_where .= $next_id;
	}
	
	$sql .= " where 1 {$c_where} {$c_order}";
	
	$c_class = check_array($class, $level);
	if(!empty($c_class)){
		$c_class = "class=\"{$c_class}\"";
	}	

	$rs = mysql_query($sql);
	if(@mysql_num_rows($rs) > 0){
		$id = "";
		if($level == 0)
			$id = " id=\"{$tag}_level{$level}\"";
		$list .= "<{$tag}{$id}>\n";
		while($row = mysql_fetch_array($rs)){
			$id 	= $row[$c_colID];
			$name 	= $row[$c_colName];
			$check = "";
			if(!empty($arr_ids[$level]))
				if(in_array($id, $arr_ids[$level]))
					$check = "checked=\"checked\"";
			switch($tag){
				case "div":
					$list .= "<div {$c_class} style=\"padding-left:{$paddingLeft}px;\">\n";
					$list .= "<span>\n\t<input disabled=\"disabled\" name=\"{$c_chkName}[]\" id=\"{$c_chkName}_{$id}\" {$check} type=\"checkbox\" value=\"{$id}\">\n";
					$list .= "\t<label for=\"{$c_chkName}_{$id}\">{$name}</label>\n</span>\n";					
					createTreeCategoryView($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, $order, $id, $ratio, $level + 1);
					$list .= "</div>\n";					
					break;
				case "ul":
					$list .= "<li {$c_class} style=\"padding-left:{$paddingLeft}px;\">\n";
					$list .= "<span>\n\t<input disabled=\"disabled\" name=\"{$c_chkName}[]\" id=\"{$c_chkName}_{$id}\" {$check} type=\"checkbox\" value=\"{$id}\">\n";
					$list .= "\t<label for=\"{$c_chkName}_{$id}\">{$name}</label>\n</span>\n";					
					createTreeCategoryView($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, $order, $id, $ratio, $level + 1);
					$list .= "</li>\n";					
					break;
				default:
					break;
			}			
		}//while($row = mysql_fetch_array($rs))
		$list .= "</{$tag}>\n";
	}//if(@mysql_num_rows($rs) > 0)
}

/*
$tableName 	= array("main_category", "mst_category", "sub_category");
$colID 		= array("mainCategoryID", array("categoryID", "mainCategoryID"), array("subCategoryID", "categoryID"));
$colName 	= array("mainCategoryNameVn", "categoryNameVn", "subCategoryNameVn");
$chkName 	= array("main_category", "mst_category", "sub_category");
$arr_ids 	= array(array("1001", "1002"), array("10001"), array("100003"));
$where 		= array(" AND `visible` = 'y'", " AND `visible` = 'y'", " AND `visible` = 'y'");
$tag 		= "ul";
$class		= array("main_category", "mst_category", "sub_category");
$order		= array("order by cast(`position` as signed) asc", "order by cast(`position` as signed) asc", "order by cast(`position` as signed) asc");

$list = "";
createTreeCategoryView($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, "", $order);
/**/

function createTreeCategoryView_v2($tableName, $colID, $colName, $chkName, $arr_ids = array(array()), &$list, $tag = "div", $class = "", $where = "1", $order = "", $next_id, $ratio = "20", $level = 0)
{		
	if(!isset($tableName[$level]))
		return;
	$paddingLeft = $ratio * $level;
	$c_tableName = check_array($tableName, $level);
	$c_colID 	 = check_array($colID, $level);
	$c_colName	 = check_array($colName, $level);
	$c_chkName 	 = check_array($chkName, $level);	
	$c_where 	 = check_array($where, $level);
	$c_order 	 = check_array($order, $level);
	if(strrpos("select", $c_tableName))
		$sql = $c_tableName;
	else
		$sql = "select * from `{$c_tableName}`";
	
	if($level > 0){		
		if(is_array($c_colID)){			
			$c_where .= " AND " . $c_colID[1] . " = {$next_id}";
			$c_colID = $c_colID[0];
		}
		else
			$c_where .= $next_id;
	}
	$ids = " AND 1=-1";
	if(!empty($arr_ids[$level])){
		$ids = implode(",", $arr_ids[$level]);
		$ids = " AND {$c_colID} in ({$ids})";
	}
	$c_where .= $ids;
	$sql .= " where 1 {$c_where} {$c_order}";
	
	$c_class = check_array($class, $level);
	if(!empty($c_class)){
		$c_class = "class=\"{$c_class}\"";
	}	

	$rs = mysql_query($sql);
	if(@mysql_num_rows($rs) > 0){
		$id = "";
		if($level == 0)
			$id = " id=\"{$tag}_level{$level}\"";
		$list .= "<{$tag}{$id}>\n";
		while($row = mysql_fetch_array($rs)){
			$id 	= $row[$c_colID];
			$name 	= $row[$c_colName];
			$check = "checked=\"checked\"";				
			switch($tag){
				case "div":
					$list .= "<div {$c_class} style=\"padding-left:{$paddingLeft}px;\">\n";
					$list .= "<span>\n\t<input disabled=\"disabled\" name=\"{$c_chkName}[]\" id=\"{$c_chkName}_{$id}\" {$check} type=\"checkbox\" value=\"{$id}\">\n";
					$list .= "\t<label for=\"{$c_chkName}_{$id}\">{$name}</label>\n</span>\n";					
					createTreeCategoryView_v2($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, $order, $id, $ratio, $level + 1);
					$list .= "</div>\n";					
					break;
				case "ul":
					$list .= "<li {$c_class} style=\"padding-left:{$paddingLeft}px;\">\n";
					$list .= "<span>\n\t<input disabled=\"disabled\" name=\"{$c_chkName}[]\" id=\"{$c_chkName}_{$id}\" {$check} type=\"checkbox\" value=\"{$id}\">\n";
					$list .= "\t<label for=\"{$c_chkName}_{$id}\">{$name}</label>\n</span>\n";					
					createTreeCategoryView_v2($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, $order, $id, $ratio, $level + 1);
					$list .= "</li>\n";					
					break;
				default:
					break;
			}			
		}//while($row = mysql_fetch_array($rs))
		$list .= "</{$tag}>\n";
	}//if(@mysql_num_rows($rs) > 0)
}

/*
$tableName 	= array("main_category", "mst_category", "sub_category");
$colID 		= array("mainCategoryID", array("categoryID", "mainCategoryID"), array("subCategoryID", "categoryID"));
$colName 	= array("mainCategoryNameVn", "categoryNameVn", "subCategoryNameVn");
$chkName 	= array("main_category", "mst_category", "sub_category");
$arr_ids 	= array(array("1001", "1002"), array("10001"), array("100003"));
$where 		= array(" AND `visible` = 'y'", " AND `visible` = 'y'", " AND `visible` = 'y'");
$tag 		= "ul";
$class		= array("main_category", "mst_category", "sub_category");
$order		= array("order by cast(`position` as signed) asc", "order by cast(`position` as signed) asc", "order by cast(`position` as signed) asc");

$list = "";
createTreeCategoryView_v2($tableName, $colID, $colName, $chkName, $arr_ids, $list, $tag, $class, $where, "", $order);
/**/

function check_date_Ymd($date){
	$arr = explode("/", $date);
	if(@checkdate(@$arr[1], @$arr[2], @$arr[0]))
		return true;
	return false;
}

function check_date_dmY($date){
	$arr = explode("/", $date);
	if(@checkdate(@$arr[1], @$arr[0], @$arr[2]))
		return true;
	return false;
}

/* modify select */
function createModifySelect(&$s1, &$s2, $sql1, $colId1, $colName1, $sql2, $colId2, $colName2, $order2 = "", $def1 = "Chọn giá trị", $def2 = "Chọn giá trị", $cusom1 = "", $custom2 = ""){
	if(empty($s1))
		$s1 = "\n<select name=\"{$colId1}\" id=\"{$colId1}\">\n";
	if(!empty($def1))
		$def1 = "\t<option value=\"\">{$def1}</option>\n";
	if(empty($s2))
		$s2 = "\n<select name=\"{$colId2}\" id=\"{$colId2}\">\n";
	if(!empty($def2))
		$def2 = "\t<option value=\"\">{$def2}</option>\n";
	$s1 .= $def1;
	$s2 .= $def2;

	if(is_array($sql1)){
		if(is_array($sql2)){			
			foreach($sql1 as $key => $val){
				if(!empty($custom1))
					$val = sprintf($custom1, $val);
				$s1 .= "\t<option value=\"{$key}\">{$val}</option>\n";				
				if(isset($sql2[$key])){
					$s2 .= "\t<optgroup label='{$key}'>\n";
					foreach($sql2[$key] as $k => $v){
						if(!empty($custom2))
							$v = sprintf($custom2, $v);
						$s2 .= "\t\t<option value=\"{$k}\">{$v}</option>\n";
					}
					$s2 .= "\t</optgroup>\n";											
				}
			}
		}
		else{
			foreach($sql1 as $key => $val){
				if(!empty($custom1))
					$val = sprintf($custom1, $val);
				$s1 .= "\t<option value=\"{$key}\">{$val}</option>\n";
				$sql3 = $sql2 . "'". mysql_real_escape_string($key) ."' " . $order2;
				$rs2 = mysql_query($sql3);				
				if(@mysql_num_rows($rs2) > 0){					
					$s2 .= "\t<optgroup label='{$key}'>\n";
					while($row2 = mysql_fetch_array($rs2)){
						$id2 = $row2[$colId2];
						$name2 = $row2[$colName2];
						if(!empty($custom2))
							$name2 = sprintf($custom2, $name2);
						$s2 .= "\t\t<option value=\"{$id2}\">{$name2}</option>\n";
					}//while($row2 = mysql_fetch_array($rs2))					
					$s2 .= "\t</optgroup>\n";
				}//if(@mysql_num_rows($rs2) > 0)												
			}
		}
	}
	else{
		$rs1 = mysql_query($sql1);
		if(@mysql_num_rows($rs1) > 0){
			if(is_array($sql2)){
				while($row1 = mysql_fetch_array($rs1)){					
					$id1 = $row1[$colId1];
					$name1 = $row1[$colName1];
					if(!empty($custom1))
						$name1 = sprintf($custom1, $name1);
					$s1 .= "\t<option value=\"{$id1}\">{$name1}</option>\n";
					if(isset($sql2[$id1])){
						$s2 .= "\t<optgroup label='{$id1}'>\n";
						foreach($sql2[$id1] as $k => $v){
							if(!empty($custom2))
								$v = sprintf($custom2, $v);
							$s2 .= "\t\t<option value=\"{$k}\">{$v}</option>\n";																								
						}
						$s2 .= "\t</optgroup>\n";
					}
				}
			}
			else{
				while($row1 = mysql_fetch_array($rs1)){					
					$id1 = $row1[$colId1];
					$name1 = $row1[$colName1];
					if(!empty($custom1))
						$name1 = sprintf($custom1, $name1);
					$s1 .= "\t<option value=\"{$id1}\">{$name1}</option>\n";
					$sql3 = $sql2 . "'" .  mysql_real_escape_string($id1) . "' " . $order2;
					$rs2 = mysql_query($sql3);
					if(@mysql_num_rows($rs2) > 0){
						$s2 .= "\t<optgroup label='{$id1}'>\n";
						while($row2 = mysql_fetch_array($rs2)){
							$id2 = $row2[$colId2];
							$name2 = $row2[$colName2];
							if(!empty($custom2))
								$name2 = sprintf($custom2, $name2);
							$s2 .= "\t\t<option value=\"{$id2}\">{$name2}</option>\n";
						}//while($row2 = mysql_fetch_array($rs2))
						$s2 .= "\t</optgroup>\n";
					}//if(@mysql_num_rows($rs2) > 0)
				}
			}
		}
	}
	$s1 .= "</select>";
	$s2 .= "</select>";
}

function createModifySelect_v2(&$s1, &$s2, $sql1, $colId1, $colName1, $sql2, $colId2, $colName2, $colCheck, $order1 = "", $order2 = "", $def1 = "Chọn giá trị", $def2 = "Chọn giá trị", $cusom1 = "", $custom2 = ""){
	if(empty($s1))
		$s1 = "\n<select name=\"{$colId1}\" id=\"{$colId1}\">\n";
	if(!empty($def1))
		$def1 = "\t<option value=\"\">{$def1}</option>\n";
	if(empty($s2))
		$s2 = "\n<select name=\"{$colId2}\" id=\"{$colId2}\">\n";
	if(!empty($def2))
		$def2 = "\t<option value=\"\">{$def2}</option>\n";
	$s1 .= $def1;
	$s2 .= $def2;
	if(strpos(strtolower($sql2), "where") !== false && !is_array($sql2))
		$sql2 .= " AND ";
	else
		$sql2 .= " where ";

	if(is_array($sql1)){
		if(is_array($sql2)){			
			foreach($sql1 as $key => $val){
				if(!empty($custom1))
					$val = sprintf($custom1, $val);
				$s1 .= "\t<option value=\"{$key}\">{$val}</option>\n";				
				if(isset($sql2[$key])){
					$s2 .= "\t<optgroup label='{$key}'>\n";
					foreach($sql2[$key] as $k => $v){
						if(!empty($custom2))
							$v = sprintf($custom2, $v);
						$s2 .= "\t\t<option value=\"{$k}\">{$v}</option>\n";
					}
					$s2 .= "\t</optgroup>\n";											
				}
			}
		}
		else{
			foreach($sql1 as $key => $val){
				if(!empty($custom1))
					$val = sprintf($custom1, $val);
				$s1 .= "\t<option value=\"{$key}\">{$val}</option>\n";					
				$sql3 = $sql2 . " `{$colCheck}` = '". mysql_real_escape_string($key) ."' " . $order2;
				$rs2 = mysql_query($sql3);				
				if(@mysql_num_rows($rs2) > 0){					
					$s2 .= "\t<optgroup label='{$key}'>\n";
					while($row2 = mysql_fetch_array($rs2)){
						$id2 = $row2[$colId2];
						$name2 = $row2[$colName2];
						if(!empty($custom2))
							$name2 = sprintf($custom2, $name2);
						$s2 .= "\t\t<option value=\"{$id2}\">{$name2}</option>\n";
					}//while($row2 = mysql_fetch_array($rs2))					
					$s2 .= "\t</optgroup>\n";
				}//if(@mysql_num_rows($rs2) > 0)												
			}
		}
	}
	else{
		$sql1 .= " " . $order1;
		$rs1 = mysql_query($sql1);
		if(@mysql_num_rows($rs1) > 0){
			if(is_array($sql2)){
				while($row1 = mysql_fetch_array($rs1)){					
					$id1 = $row1[$colId1];
					$name1 = $row1[$colName1];
					if(!empty($custom1))
						$name1 = sprintf($custom1, $name1);
					$s1 .= "\t<option value=\"{$id1}\">{$name1}</option>\n";
					if(isset($sql2[$id1])){
						$s2 .= "\t<optgroup label='{$id1}'>\n";
						foreach($sql2[$id1] as $k => $v){
							if(!empty($custom2))
								$v = sprintf($custom2, $v);
							$s2 .= "\t\t<option value=\"{$k}\">{$v}</option>\n";																								
						}
						$s2 .= "\t</optgroup>\n";
					}
				}
			}
			else{					
				while($row1 = mysql_fetch_array($rs1)){					
					$id1 = $row1[$colId1];
					$name1 = $row1[$colName1];
					if(!empty($custom1))
						$name1 = sprintf($custom1, $name1);
					$s1 .= "\t<option value=\"{$id1}\">{$name1}</option>\n";
					$sql3 = $sql2 . " `{$colCheck}` = '" .  mysql_real_escape_string($id1) . "' " . $order2;
					$rs2 = mysql_query($sql3);
					if(@mysql_num_rows($rs2) > 0){
						$s2 .= "\t<optgroup label='{$id1}'>\n";
						while($row2 = mysql_fetch_array($rs2)){
							$id2 = $row2[$colId2];
							$name2 = $row2[$colName2];
							if(!empty($custom2))
								$name2 = sprintf($custom2, $name2);
							$s2 .= "\t\t<option value=\"{$id2}\">{$name2}</option>\n";
						}//while($row2 = mysql_fetch_array($rs2))
						$s2 .= "\t</optgroup>\n";
					}//if(@mysql_num_rows($rs2) > 0)
				}
			}
		}
	}
	$s1 .= "</select>";
	$s2 .= "</select>";
}


/*
$sql1 = "select distinct year(`regDate`) as `year` from `order` where orderFlg = 'y'";
$sql2 = "select distinct month(`regDate`) as `month` from `order` where orderFlg = 'y' AND year(`regDate`) = ";
$yearView = "";
$monthView = "";
createModifySelect($yearView, $monthView, $sql1, "year", "year", $sql2, "month", "month", $def1, $def2, "", "%02d");

$yearView = "";
$monthView = "";
$m_array = array("2012" => array("7" => "07"));
createModifySelect($yearView, $monthView, $sql1, "year", "year", $m_array, "month", "month", $def1, $def2, "", "%02d");

$y_array = array("2012" => "2012", "2011" => "2011");
$m_array = array("2012" => array("7" => "07", "6" => "06"));
createModifySelect($yearView, $monthView, $y_array, "year", "year", $m_array, "month", "month", $def1, $def2, "", "%02d");
/**/


//----------------------------------------createForm----------------------------------------//
function createForm_getFields_checkEdit($arr_fields, $getID, $link_ret, $sql = ""){
	$arr_data = array();
	$tablename = $arr_fields["__table"];
	unset($arr_fields["__table"]);
	$colID = $arr_fields["__colID"];
	unset($arr_fields["__colID"]);
	if(empty($_SESSION[$colID])){
		if(strpos(strtolower($sql), " from ") > 0){		
		}
		else{
			@$id = $_GET[$getID];
			if(empty($id) && !empty($link_ret)){
				linkto($link_ret);
			}
			else{
				$id = mysql_real_escape_string($id);
				$sql = "select * from `{$tablename}` where `{$colID}` = '$id'";				
			}
		}
		$rs = mysql_query($sql);		
		if(@mysql_num_rows($rs) > 0){
			$row = mysql_fetch_array($rs);
			foreach($arr_fields as $key => $val){				
				if(isset($val["data"])){					
					$arr_data[$key] = $val["data"];
					continue;
				}
				@$type = $val["type"];
				if($type == "password_confirm"){
					$password = $val["password"];
					$arr_data[$key] = $row[$password];					
				}
				else if($type == "modifyselect"){
					$modifyselect = $val["modifyselect"];
					$arr_data[$key] = $row[$key];
					$m_colID 	= $modifyselect["colID"];
					$sql 		= $modifyselect["sql"];
					$colCheck 	= $modifyselect["colCheck"];
					@$title 	= $modifyselect["title"];
					$val_check = $row[$key];
					$len = count($title);					
					for($i=0; $i<$len -1; $i++){
						$colCheck_val = $colCheck[$i];
						$val_check = single_select_v2($sql[$i][1], $colCheck[$i], " " . " AND `".$m_colID[$i][1]."` = '{$val_check}'");		
						$arr_data[$colCheck[$i]] = $val_check;
					}							
				}
				else
					$arr_data[$key] = $row[$key];
			}
			$arr_data[$colID] = $row[$colID];
		}
		else if(!empty($link_ret)){
			linkto($link_ret);
		}
	}
	return $arr_data;
}

function createForm_getFields($arr_fields, $err = "", $err_codes = array(), $arr_data = array(), $before = "", $after = ""){
	$form_fields  = "";
	$tablename = $arr_fields["__table"];
	unset($arr_fields["__table"]);
	$colID = $arr_fields["__colID"];
	unset($arr_fields["__colID"]);
	$value = "";
	if(isset($_SESSION[$colID]))
		$value = $_SESSION[$colID];
	else if(!empty($arr_data)){
		$value = $arr_data[$colID];
	}
	unset($_SESSION[$colID]);
	$value = htmlentities($value, ENT_QUOTES | ENT_IGNORE, "UTF-8");
	$form_fields .= "<input type=\"hidden\" value=\"". $value ."\" name=\"{$colID}\" id=\"{$colID}\" />\n";
	
	if(empty($before))
		$form_fields .= "<table>\n<tbody>\n";
	else
		$form_fields .= $before;	
	foreach($arr_fields as $key => $val){	
		$form_fields .= "\t<tr>\n";
		@$required = $val["required"];
		@$type = $val["type"];
		@$arr_val = $val["arr_val"];
		@$callback = $val["callback"];
		if(is_callable($callback)){
			$callback($val, $key, $form_fields);
			continue;
		}
		$extra = "";
		if(array_key_exists("arr_style", $val)){
			foreach($val["arr_style"] as $k => $v){
				$extra .= "$k=\"{$v}\"";				
			}			
		}
		
		@$value = $val["def"];
		if(isset($_SESSION[$key]))
			@$value = $_SESSION[$key];
		else if(isset($arr_data[$key])){
			@$value = $arr_data[$key];
		}
		
		$err_text = "";
		if(!empty($val["err"])){
			if(is_array($val["err"])){
				foreach($val["err"] as $k => $err_code){					
					if(is_array($err_code))
						$err_code = $err_code["err_code"];
					if(preg_match("/" . $err_code . "/", $err)){				
						$err_text .= $err_codes[$err_code];
					}					
				}
			}			
		}
				
		$value = htmlentities($value, ENT_QUOTES | ENT_IGNORE, "UTF-8");
		if(!empty($val["title"]))
			$form_fields .= "\t\t<th>". @$val["title"]. $required . "</th>\n";
		switch($type){			
			case "date":
				if(!empty($value)){	
					if($value == "0000-00-00 00:00:00" || $value == "0000-00-00"){
						$value = "";
					}
					else{
						try{						
							if($val["date"] == "dmy" && !check_date_dmY($value)){							
								$value = new DateTime($value);
								$value = $value->format("d/m/Y");
								
							}
							else if($val["date"] == "ymd" && !check_date_dmY($value)){
								$value = new DateTime($value);
								$value = $value->format("Y/m/d");
							}
						}
						catch (Exception $e) {
							//var_dump($e->getMessage());
						}
					}
				}
			case "text":
			default:			
				$form_fields .= "\t\t<td><input {$extra} type=\"text\" value=\"". $value ."\" name=\"{$key}\" id=\"{$key}\" />{$err_text}</td>\n";
				break;
			case "password":
			case "password_old":
			case "password_new":
			case "password_confirm":
				$form_fields .= "\t\t<td><input {$extra} type=\"password\" value=\"". $value ."\" name=\"{$key}\" id=\"{$key}\" />{$err_text}</td>\n";
				break;
			case "hidden":
				$form_fields .= "\t\t<input {$extra} type=\"hidden\" value=\"". $value ."\" name=\"{$key}\" id=\"{$key}\" />{$err_text}\n";
				break;
			case "radio":
				$view = "";
				if(is_array($arr_val)){
					$view = @array_radio($arr_val, $value, $key);
				}
				$form_fields .= "\t\t<td>{$view}{$err_text}</td>\n";				
				break;
			case "textarea":
			case "ckeditor":
				$form_fields .= "\t\t<td><textarea {$extra} type=\"hidden\" name=\"{$key}\" id=\"{$key}\">{$value}</textarea>{$err_text}</td>\n";
				break;
			case "select":
				$view = "";
				if(is_array($arr_val)){					
					$view = @array_single_option_v2($arr_val, $value, $key);
				}
				else{
					@$select = $val["select"];
					$view = single_option_v2($value, $key, @$select["table_name"], @$select["where_cond"], @$select["column_name"], @$select["column_id"], @$select["onchange"], isset($select["option_id"]) ? $select["option_id"] : $key);
				}
				$form_fields .= "\t\t<td>{$view}{$err_text}</td>\n";	
				break;
			case "file":
				$text = "Delete image";
				$path = $val["path"];
				$dir = $val["dir"];
				@$view_x = $val["view_x"];
				@$view_y = $val["view_y"];
				if(isset($val["text"]))
					$text = $val["text"];
				$imageView = "";
				if(empty($value))
					@$value = $_SESSION["check_" . $key];
				if(!empty($value)){
					$file = $dir . $value;
					$js_file = json_encode($file);
					$js_file = substr($js_file, 1, strlen($js_file) - 2);
					if(file_exists($file) && !is_dir($file)){
						$imageView = "<div id='divImage_{$key}'>".view_image($path, $value, $dir, $view_x, $view_y)."<br /><a href='javascript:void(0);' onclick=\"return message_del('{$js_file}', 'divImage_{$key}')\">{$text}</a><br /></div>";
					}
				}		
				$form_fields .= "\t\t<td>{$imageView}<input {$extra} type=\"file\" name=\"{$key}\" id=\"{$key}\" /> {$err_text}\n\t\t<input type=\"hidden\" name=\"check_{$key}\" value=\"{$value}\" /></td>\n";
				break;
			case "generate":				
				if(empty($colIDVal)){
					@$text = $val["text"];
					@$auto = $val["auto"];
					$checked = "";
					$readonly = "";					
					if(isset($_SESSION[$key])){
						if(!empty($_SESSION["__generate_" . $key])){
							$checked  = "checked =\"checked \"";						
							$readonly = "readonly=\"readonly\"";
						}
					}
					else if(!empty($auto)){
						$checked  = "checked =\"checked \"";						
						$readonly = "readonly=\"readonly\"";
					}
					
					$form_fields .= "\t\t<td><input {$checked } onclick=\"generate_check(this, '$key');\" type=\"checkbox\" value=\"1\" name=\"__generate_{$key}\" id=\"__generate_{$key}\"  /><label for=\"__generate_{$key}\">{$text} </label>\n\t\t<input {$readonly} {$extra} type=\"text\" value=\"". $value ."\" name=\"{$key}\" id=\"{$key}\" />{$err_text}</td>\n";
					unset($_SESSION["__generate_" . $key]);
				}
				else{
					$form_fields .= "\t\t<td><input {$extra} type=\"text\" value=\"". $value ."\" name=\"{$key}\" id=\"{$key}\" />{$err_text}</td>\n";
				}
				break;
			case "tree":
				$tree = $val["tree"];
				$view = "";
				$arr_ids = array();
				foreach($tree["chkName"] as $k => $v){
					$arr_ids[] = empty($_SESSION[$v]) ? array() : $_SESSION[$v];
					unset($_SESSION[$v]);
				}
				
				createTreeCategory($tree["tableName"], $tree["colID"], $tree["colName"], $tree["chkName"], $arr_ids, $view, @$tree["tag"], @$tree["class"], @$tree["where"], @$tree["order"]);
				$form_fields .= "\t\t<td>{$view}{$err_text}</td>\n";
				break;
			case "multiple":
				if(empty($value))
					$value = array();
				$multiple 	= $val["multiple"];
				$c_id 		= isset($multiple["id"]) ? $multiple["id"] : $key;
				$c_name 	= isset($multiple["name"]) ? $multiple["name"] : $key;
				$size	 	= isset($multiple["size"]) ? $multiple["size"] : 5;
				$view = multiple_option($value, $key, $size, $multiple["tablename"], @$multiple["where"], $c_name, $c_id);
				$form_fields .= "\t\t<td>{$view}{$err_text}</td>\n";
				break;
			case "db_checkbox":
				$db_checkbox 	= $val["db_checkbox"];
				$c_id 		= isset($db_checkbox["id"]) ? $db_checkbox["id"] : $key;
				$c_name 	= isset($db_checkbox["name"]) ? $db_checkbox["name"] : $key;
				$view = db_checkbox($value, $key, $db_checkbox["tablename"], @$db_checkbox["where"], $c_name, $c_id);
				$form_fields .= "\t\t<td>{$view}{$err_text}</td>\n";
				break;
			case "modifyselect":				
				$s1_view = "";
				$s2_view = "";
				$view = "";
				$script = "";
				$modifyselect = $val["modifyselect"];
				$sql 		= $modifyselect["sql"];
				$m_colID 	= $modifyselect["colID"];				
				$m_colName 	= $modifyselect["colName"];
				@$m_order 	= $modifyselect["order"];				
				@$m_custom	= $modifyselect["m_custom"];
				@$text		= $modifyselect["text"];
				@$m_arr_style	= $modifyselect["arr_style"];
				@$m_colCheck	= $modifyselect["colCheck"];
				
				@$title = $modifyselect["title"];				
				$len = count($title);
				for($i=0; $i<$len - 1; $i++){
					$ex1 = $extra;
					$ex2 = $extra;
					if(isset($m_arr_style[$i])){						
						foreach($m_arr_style[$i][0] as $k => $v){
							$ex1 .= "$k=\"{$v}\"";				
						}
						foreach($m_arr_style[$i][1] as $k => $v){
							$ex2 .= "$k=\"{$v}\"";				
						}
					}
					
					$s1_view = "\n\t\t<select {$ex1} name=\"".$m_colID[$i][0]."\" id=\"".$m_colID[$i][0]."\">\n";
					$s2_view = "\n\t\t<select {$ex2} name=\"".$m_colID[$i][1]."\" id=\"".$m_colID[$i][1]."\">\n";					
					createModifySelect_v2($s1_view, $s2_view, $sql[$i][0], $m_colID[$i][0], $m_colName[$i][0], $sql[$i][1], $m_colID[$i][1], $m_colName[$i][1], $m_colCheck[$i], $m_order[$i][0], $m_order[$i][1], $text[$i][0], $text[$i][1]);
					
					
					$view = "\t\t<th>". @$title[$i]. $required . "</th>\n" . "\t\t<td>{$s2_view}{$err_text}</td>\n" . $view;					
					$view = "\t</tr>\n\t<tr>\n" . $view;
					
					@$m_val1 = $modifyselect["def"][0];
					if(isset($_SESSION[$m_colID[$i][0]]))
						@$m_val1 = $_SESSION[$m_colID[$i][0]];
					else if(isset($arr_data[$m_colID[$i][0]])){
						@$m_val1 = $arr_data[$m_colID[$i][0]];
					}
					
					@$m_val2 = $modifyselect["def"][1];
					if(isset($_SESSION[$m_colID[$i][1]]))
						@$m_val2 = $_SESSION[$m_colID[$i][1]];
					else if(isset($arr_data[$m_colID[$i][1]])){
						@$m_val2 = $arr_data[$m_colID[$i][1]];
					}
					
					$script .= "<script type=\"text/javascript\">ModifySelect(\"".$m_colID[$i][0]."\", \"".$m_colID[$i][1]."\", \"{$m_val1}\", \"{$m_val2}\");</script>\n";
					$err_text = "";
					$required = "";
				}

				$view = "\t\t<th>". @$title[$len - 1] . "</th>\n" . "\t\t<td>{$s1_view}</td>\n\t</tr>\n" . $view;
				$form_fields .= $view;
				$form_fields .= $script;
				break;
		}
		unset($_SESSION[$key]);
		$form_fields .= "\t</tr>\n";
	}
	if(empty($after))
		$form_fields .= "</tbody>\n</table>\n";
	else
		$form_fields .= $after;
	unset($_SESSION["err"]);		
	return $form_fields;
}

function createForm_checkErr(&$err, $key, $value, $val, $tablename, $colID){
	if(array_key_exists("err", $val)){
		foreach($val["err"] as $err_type => $code){
			switch($err_type){
				case "empty":
					if(empty($value)){
						$err .= "+" . $code;
					}
					break;
				case "email":				
					if(!empty($value) && !preg_match("/^([a-z0-9_\.-])+@(([a-z0-9_-])+\\.)+[a-z]{2,6}$/i", $value))
						$err .= "+" . $code;					
					break;
				case "numeric":
					if(!empty($value) && !is_numeric($value))
						$err .= "+" . $code;					
					break;
				case "min_len":
					$v = $code["v"];
					if(strlen($value) < $v && !empty($value))
						$err .= "+" . $code["err_code"];										
					break;
				case "max_len":
					$v = $code["v"];
					if(strlen($value) > $v && !empty($value))
						$err .= "+" . $code["err_code"];
					break;
				case "confirm":
					if(!empty($value)){
						$v = $code["v"];						
						if($value != @$_POST[$v] && $value != @$_SESSION[$v] && !empty($value))
							$err .= "+" . $code["err_code"];
					}
					break;
				case "check_data":
					if(!empty($value)){
						$chk = $code["v"];
						$value_encrypt = encrypt($value);
						$colID_value = empty($_POST[$colID]) ? $_SESSION[$colID] : $_POST[$colID];
						$colID_value = mysql_real_escape_string($colID_value);
						$chk_data = single_select($tablename, $key, "`{$colID}` = '{$colID_value}' AND (`{$key}` = '{$value}' OR `{$key}` = '{$value_encrypt}')");
						if($chk_data == "" && $chk === true)
							$err .= "+" . $code["err_code"];
						else if($chk_data != "" && $chk === false)
							$err .= "+" . $code["err_code"];
					}
					break;
				case "date":
					if(empty($value))
						break;
					$v = strtolower($code["v"]);					
					switch($v){
						case "dmy":
							if(!check_date_dmY($value))
								$err .= "+" . $code["err_code"];
						break;
						case "ymd":
							if(!check_date_Ymd($value))
								$err .= "+" . $code["err_code"];
						break;						
					}
					break;
				case "unique":
					if(!empty($value)){
						$colID_value = empty($_POST[$colID]) ? $_SESSION[$colID] : $_POST[$colID];
						$_value = mysql_real_escape_string($value);
						$where = "`{$key}` = '$_value'";
						if(!empty($colID_value)){
							$colID_value = mysql_real_escape_string($colID_value);
							$where .= " AND `{$colID}` != '$colID_value'";
						}
						$chk = single_select($tablename, $key, $where);
						if(!empty($chk)){
							$err .= "+" . $code;
						}
					}
					break;
				default:
					break;
			}
		}
	}
}

function createForm_getView($arr_fields, $link_ret = "", $arr_data = array(), $before = "", $after = ""){
	$tablename = $arr_fields["__table"];
	unset($arr_fields["__table"]);
	@$colID 			= $arr_fields["__colID"];
	@$value 			= $_POST[$colID];
	$form_views  = "";
	if(!empty($arr_data))
	{
		$form_views .= "<input type=\"hidden\" value='".$arr_data[$colID]."' name=\"{$colID}\" />";
	}
	$_SESSION[$colID] = $value;
	unset($arr_fields["__colID"]);	
	
	if(empty($before))
		$form_views .= "<table>\n<tbody>\n";
	else
		$form_views .= $before;
	$err = "";
	foreach($arr_fields as $key => $val){		
		$form_views .= "\t<tr>\n";				
		@$type = $val["type"];
		
		@$arr_val = $val["arr_val"];		
		@$def = $val["def"];
		@$callback = $val["callback"];
		if(is_callable($callback)){
			$callback($val, $key, $form_views, $err);
			continue;
		}
		
		$extra = "";
		/*
		if(array_key_exists("arr_style", $val)){
			foreach($val["arr_style"] as $k => $v){
				$extra .= "$k=\"{$v}\"";
			}
		}
		/**/		
		
		@$value = $_POST[$key];
		if(!empty($arr_data))
			$value = $arr_data[$key];
		else{			
			$_SESSION[$key] = $value;
			createForm_checkErr($err, $key, $value, $val, $tablename, $colID);
		}
		
		if(!empty($val["title"]))
			$form_views .= "\t\t<th>" . @$val["title"] . "</th>\n";
		switch($type){
			default:
			case "text":					
				$form_views .= "\t\t<td {$extra}>{$value}</td>\n";
				break;
			case "password":
			case "password_old":
			case "password_new":
			case "password_confirm":
				$password_char = "●●●●●●●●●●●●●●●●●●●●";
				$form_views .= "\t\t<td {$extra}>{$password_char}</td>\n";
				break;
			case "hidden":
				break;
			case "radio":
				$view = "";
				if(is_array($arr_val)){
					$view = @array_single_select($arr_val, $value);
				}
				$form_views .= "\t\t<td {$extra}>{$view}</td>\n";
				break;
			case "textarea":			
				$view = str_replace("\r\n", "<br />", $value);
			case "ckeditor":
				$form_views .= "\t\t<td {$extra}>{$view}</td>\n";
				break;
			case "select":
				$view = "";
				if(is_array($arr_val)){					
					$view = @array_single_select($arr_val, $value);
				}
				else{
					@$select = $val["select"];
					if(is_array($select)){
						$view = single_select(@$select["table_name"], @$select["column_name"], @$select["column_id"] . "='{$value}'");
					}
				}
				$form_views .= "\t\t<td>{$view}</td>\n";
				break;			
			case "file":
				$path = $val["path"]; $dir = $val["dir"]; $width = 0; $height = 0;
				@$view_x = $val["view_x"];
				@$view_y = $val["view_y"];
				if(isset($val["width"]))
					$width = $val["width"];
				if(isset($val["height"]))
					$height = $val["height"];
				@$value = !empty($_FILES[$key]["name"]) ? $_FILES[$key]["name"] : $_POST["check_{$key}"];
				if(!empty($_FILES[$key]["name"])){
					$date = date("YmdHis", time());
					upload_image($key, $dir, $date."_1", $width, $height);
					@$value = $_SESSION[$key];
				}

				$imageView = "";
				if(!empty($value)){
					$imageView = view_image($path, $value, $dir, $view_x, $view_y);					
				}
				$_SESSION[$key] = $value;
				$form_views .= "\t\t<td>{$imageView}</td>\n";
				break;
			case "generate":
				if(empty($colIDVal) && !empty($_POST["__generate_" . $key])){
					@$text = $val["text"];
					@$auto = $val["auto"];
					$checked = "";
					$readonly = "";		
					if(isset($_SESSION[$key]) && !empty($_SESSION["__generate_" . $key])){
						$checked  = "checked =\"checked \"";						
						$readonly = "readonly=\"readonly\"";
					}
					else if(!empty($auto)){
						$checked  = "checked =\"checked \"";						
						$readonly = "readonly=\"readonly\"";
					}
					
					$form_views .= "\t\t<td {$extra}><input checked=\"checked\" disabled=\"disabled\" type=\"checkbox\" value=\"1\" /><label>{$text} </label></td>\n";
					$_SESSION[$key] = "";
					$_SESSION["__generate_" . $key] = 1;
				}
				else{
					$form_views .= "\t\t<td {$extra}>{$value}</td>\n";
				}														
				break;
			case "tree":
				$tree = $val["tree"];
				$view = "";
				$arr_ids = array();
				foreach($tree["chkName"] as $k => $v){
					$arr_ids[] = empty($_POST[$v]) ? array() : $_POST[$v];
					$_SESSION[$v] = empty($_POST[$v]) ? array() : $_POST[$v];
				}
				createTreeCategoryView_v2($tree["tableName"], $tree["colID"], $tree["colName"], $tree["chkName"], $arr_ids, $view, @$tree["tag"], $tree["class"], $tree["where"], $tree["order"]);
				$form_views .= "\t\t<td>{$view}</td>\n";
				break;
			case "multiple":
				$multiple = $val["multiple"];
				$c_id 		= isset($multiple["id"]) ? $multiple["id"] : $key;
				$c_name 	= isset($multiple["name"]) ? $multiple["name"] : $key;
				$size	 	= isset($multiple["size"]) ? $multiple["size"] : 5;
				$where 		= empty($multiple["where"]) ? "" : " AND " . $multiple["where"];				
				$view = multiple_select_v2($multiple["tablename"], $c_id, $value, $c_name, $where);
				$form_views .= "\t\t<td>{$view}</td>\n";
				break;
			case "db_checkbox":
				$db_checkbox 	= $val["db_checkbox"];
				$c_id 		= isset($db_checkbox["id"]) ? $db_checkbox["id"] : $key;
				$c_name 	= isset($db_checkbox["name"]) ? $db_checkbox["name"] : $key;
				$view = multiple_select_v2($db_checkbox["tablename"], $c_id, $value, $c_name, @$db_checkbox["where"]);
				$form_views .= "\t\t<td>{$view}</td>\n";
				break;		
			case "modifyselect":
				$view = "";				
				$modifyselect = $val["modifyselect"];
				$sql 		= $modifyselect["sql"];
				$m_colID 	= $modifyselect["colID"];				
				$m_colName 	= $modifyselect["colName"];				
				@$title = $modifyselect["title"];				
				$len = count($title);
				for($i=0; $i<$len - 1; $i++){					
					@$m_val = $_POST[$m_colID[$i][1]];
					@$_SESSION[$m_colID[$i][1]] = $m_val;
					$s_view = single_select_v2($sql[$i][1], $m_colName[$i][1], " " . " AND `".$m_colID[$i][1]."` = '{$m_val}'");										
					if($i == 0)
						$view = "\t\t<th>". @$title[$i] . "</th>\n" . "\t\t<td>{$s_view}</td>\n" . $view;
					else
						$view = "\t\t<th>". @$title[$i] . "</th>\n" . "\t\t<td>{$s_view}</td>\n\t</tr>\n\t<tr>\n" . $view;
				}
				@$m_val = $_POST[$m_colID[$i-1][0]];	
				@$_SESSION[$m_colID[$i-1][0]] = $m_val;				
				$s_view = single_select_v2($sql[$i-1][0], $m_colName[$i-1][0], " " . " AND `".$m_colID[$i-1][0]."` = '{$m_val}'");				
				$view = "\t\t<th>". @$title[$i] . "</th>\n" . "\t\t<td>{$s_view}</td>\n\t</tr>\n\t<tr>\n" . $view;
				$form_views .= $view;
				break;	
		}
		$form_views .= "\t<tr>\n";
	}
	if(empty($after))
		$form_views .= "</tbody>\n</table>\n";
	else
		$form_views .= $after;
	if(!empty($err)){
		$_SESSION["err"] = $err;
		@header("Location: {$link_ret}");
		exit();
	}
	return $form_views;
}

function getDateVal($value, $v_date){
	if(empty($value))
		return "";
	$arr = explode("/", $value);
	$v = "";
	switch($v_date){
		case "dmy":
			$d = new DateTime(@$arr[2] . "/" . @$arr[1] . "/" . @$arr[0]);
			break;
		case "ymd":			
			break;			
		default:	
			break;
	}
	if(isset($d))
		$v = $d->format("Y/m/d");
	return $v;
}

function createForm_Generate($val, $tablename, $key, $col, $value){
	if(!empty($_SESSION["__generate_" . $key])){
		$generate = $val["generate"];
		$generate_key = "";
		$num = isset($generate["num"]) ? $generate["num"] : 3;
		$sep = isset($generate["sep"]) ? $generate["sep"] : "-";
		if(isset($generate["code"])){
			$generate_key = $generate["code"];
		}
		else if(isset($generate["id"])){
			$name = str_replace("  ", " ", $_SESSION[$generate["id"]]);
			if(!empty($name)){
				$name = trim($name);
				$arr = explode(" ", $name);
				$generate_key = "";
				foreach($arr as $c){
					$a = strtoupper($c[0]);
					if(ord($a) >= 65 && ord($a) <= 90)
						$generate_key .= $a . $sep;
				}	
			}
			else{
				$generate_key = generate_password($num);
			}
		}
		else{
			$generate_key = generate_password($num);
		}
		$sql = "select max(replace(`{$col}`, '$generate_key', '')) as max from `{$tablename}` where `{$col}` like '$generate_key%'";
		$rs = mysql_query($sql);
		if(@mysql_num_rows($rs) > 0){
			$row = mysql_fetch_array($rs);
			$max = $row["max"];
			$max++;		
			$generate_key .= sprintf("%1$0{$num}d", $max);
			mysql_free_result($rs);
		}
		else{
			$generate_key .= "001";
		}
		$value = $generate_key;	
	}
	unset($_SESSION["__generate_" . $key]);
	return $value;
}

function createForm_checkData($val, $value, $colID, $colID_val){
	@$type = $val["type"];
	@$encrypt = $val["encrypt"];
	if($type == "date"){
		$value = getDateVal($value, @$val["date"]);
	}
	else if($type == "file"){
		$folder = "";
		$dir = $val["dir"] . "/";
		if(isset($val["folder"])){
			$folders = is_array($val["folder"]) ? $val["folder"] : array($val["folder"]);
			$folder = "";
			foreach($folders as $f){
				if(isset($_SESSION[$f])){
					$folder .= $_SESSION[$f] . "/";
					if(!is_dir($dir . $folder)){
						@mkdir($dir . $folder, 0777);				
					}
				}
			}			
		}
		if(!empty($value)){
			$file_old = $value;
			$arr = explode(".", $value);
			$ext = end($arr); unset($arr);
			while(true){	
				$value = generate_password(16) . "." . $ext;
				if(!file_exists($dir . $folder . "/" . $value))
					break;	
			}
			if(@copy($dir . $file_old, $dir . $folder . "/" . $value)){
				@unlink($dir . $file_old);
			}
		}					
	}
	else if($type == "multiple"){
		$value = implode(",", $value);						
	}
	else if($type == "db_checkbox"){
		$value = implode(",", $value);
	}	
	else if($type == "modifyselect"){
		$modifyselect = $val["modifyselect"];
		$m_colID 	  = $modifyselect["colID"];		
		foreach($m_colID as $arr)
			foreach($arr as $k)
				unset($_SESSION[$k]);		
	}
	else if(is_callable($encrypt)){
		$value = $encrypt($value);
	}	
	return $value;
}

function createForm_insertData($arr_fields, $link_ret = "", $beginID = "", $arr_fake_cols = array()){	
	$tablename = $arr_fields["__table"];
	unset($arr_fields["__table"]);
	$colID = $arr_fields["__colID"];
	unset($arr_fields["__colID"]);
	$err = "";
	if(empty($beginID))
		$beginID = 1;
	$colID_val = generate_id ($tablename, $colID,  $beginID);
	$sql = "INSERT INTO `{$tablename}` (`$colID`, ";		
	$sql_values = " VALUES('$colID_val', ";
	foreach($arr_fields as $key => $val){
		@$value = $val["def"];
		@$type = $val["type"];
		@$encrypt = $val["encrypt"];
		@$callback = $val["callback"];
		if(is_callable($callback)){
			$callback($val, $key, $sql, $err);
			continue;
		}		
		if(isset($_SESSION[$key]))
			$value = $_SESSION[$key];
		else if(@array_key_exists("callback", $val)){
			if(is_callable($val["callback"]))
				$value = $val["callback"]($value);
		}
		createForm_checkErr($err, $key, $value, $val, $tablename, $colID);		
		if(strpos($type, "password") !== false){
			if(empty($value) || $type != "password")
				continue;
		}

		if($type == "generate")
			$value = createForm_Generate($val, $tablename, $key, $key, $value);			
		else
			$value = createForm_checkData($val, $value, $colID, $colID_val);
		
		if($type == "tree"){
			$tree = $val["tree"];
			foreach($tree["chkName"] as $k => $v){
				$chk_values = $_SESSION[$v];				
				if(empty($chk_values))
					$chk_values = "";
				else
					$chk_values = implode(",", $chk_values);
				if(isset($arr_fake_cols[$v]))
					$v = $arr_fake_cols[$v];
				$chk_values = mysql_real_escape_string($chk_values);
				$sql 		.= "`$v`, ";
				$sql_values .= "'$chk_values', ";
				unset($_SESSION[$v]);
			}
		}
		else{				
			$value = mysql_real_escape_string($value);
			if(isset($arr_fake_cols[$key]))
				$key = $arr_fake_cols[$key];
			$sql 		.= "`$key`, ";
			$sql_values .= "'$value', ";
		}
	}
		
	$sql  = substr($sql, 0, strlen($sql) - 2) . ")";
	$sql .= substr($sql_values, 0, strlen($sql_values) - 2) . ");";
	mysql_query($sql);

	if(!empty($err)){
		$_SESSION["err"] = $err;
		linkto($link_ret);
	}	
	foreach($arr_fields as $key => $val){
		unset($_SESSION[$key]);
	}
	unset($_SESSION[$colID]);
}

function createForm_updateData($arr_fields, $link_ret = "", $arr_fake_cols = array()){
	$tablename = $arr_fields["__table"];
	unset($arr_fields["__table"]);
	$colID = $arr_fields["__colID"];
	unset($arr_fields["__colID"]);
	
	$colID_val = $_SESSION[$colID];
	
	$err = "";
	$sql = "UPDATE `{$tablename}` SET ";
	foreach($arr_fields as $key => $val){
		@$type = $val["type"];		
		@$value = $val["def"];
		@$encrypt = $val["encrypt"];
		@$callback = $val["callback"];
		if(is_callable($callback)){
			$callback($val, $key, $sql, $err);
			continue;
		}
		if(isset($_SESSION[$key]))
			$value = $_SESSION[$key];
		else if(@array_key_exists("callback", $val)){
			if(is_callable($val["callback"]))
				$value = $val["callback"]($value);
		}
		
		createForm_checkErr($err, $key, $value, $val, $tablename, $colID);		
		if(strpos($type, "password") !== false){
			if(empty($value) || $type != "password")
				continue;					
		}
		
		$value = createForm_checkData($val, $value, $colID, $colID_val);
		
		if($type == "tree"){
			$tree = $val["tree"];
			foreach($tree["chkName"] as $k => $v){
				$chk_values = $_SESSION[$v];				
				if(empty($chk_values))
					$chk_values = "";
				else
					$chk_values = implode(",", $chk_values);
				if(isset($arr_fake_cols[$v]))
					$v = $arr_fake_cols[$v];
				$chk_values = mysql_real_escape_string($chk_values);
				$sql 		.= "`$v` = '$chk_values', ";	
				unset($_SESSION[$v]);
			}
		}
		else{				
			if(isset($arr_fake_cols[$key]))
			$key = $arr_fake_cols[$key];
			$value = mysql_real_escape_string($value);
			$sql 		.= "`$key` = '$value', ";	
		}		
	}
		
	$sql  = substr($sql, 0, strlen($sql) - 2) . " WHERE `{$colID}` = '{$colID_val}'";	
	mysql_query($sql);	
	if(!empty($err)){
		$_SESSION["err"] = $err;
		linkto($link_ret);
	}
	foreach($arr_fields as $key => $val){
		unset($_SESSION[$key]);
	}
	unset($_SESSION[$colID]);
}

//----------------------------------------end createForm----------------------------------------//

//----------------------------------------end createList----------------------------------------//

function single_array($table_name, $column_id, $column_name = "", $wherecond = ""){
	$wherecond = !empty($wherecond) ? $wherecond : "1";
	$arr = array();
	if(!empty($table_name) && !empty($column_id)){
		$sql = "select * from `$table_name` where $wherecond";
		$rs = mysql_query($sql) or die(mysql_error());
		if(@mysql_num_rows($rs) > 0){
			while($row = mysql_fetch_array($rs)){
				$arr[$row[$column_id]] = $row[$column_name];
			}
		}
		@mysql_free_result($rs);
	}
	return $arr;
}

function create_listBody_deleteData($table_name, $colID = "", $arr_fake_cols = array()){	
	if(isset($_POST["chk_del"])){
		$col = "chk_del";
		if(isset($arr_fake_cols["chk_del"]["name"])){
			$col = $arr_fake_cols["chk_del"]["name"];
		}
		$col = $arr_fake_cols["chk_del"]["col"];
		$def = $arr_fake_cols["chk_del"]["def"];
		if(is_array($_POST["chk_del"])){
			foreach($_POST["chk_del"] as $val){
				$val = mysql_real_escape_string($val);
				$sql = "UPDATE `{$table_name}` SET `{$col}` = '$def' WHERE `{$colID}` = '$val'";
				mysql_query($sql);
			}
		}
		else{
			$val = $_POST["chk_del"];
			$val = mysql_real_escape_string($val);
			$sql = "UPDATE `{$table_name}` SET `{$col}` = '$def' WHERE `{$colID}` = '$val'";
			mysql_query($sql);
		}
		unset($_POST["chk_del"]);
	}
}

function create_listBody_updateData($table_name, $colID = "", $arr_fake_cols = array()){
	if(!empty($_POST)){
		create_listBody_deleteData($table_name, $colID, $arr_fake_cols);
		$arr = $_POST;
		unset($arr["x"]); //unset image submit
		unset($arr["y"]); //unset image submit
		$ids = empty($arr["id"]) ? array() : $arr["id"];
		unset($arr["id"]);
		
		@$page = $arr["page"];
		unset($arr["page"]);
		@$query_string = $arr["query_string"];
		unset($arr["query_string"]);		
		
		$len = count($ids);
		for($i=0; $i<$len; $i++){
			$id = $ids[$i];
			$sql = "UPDATE `{$table_name}` SET ";
			foreach($arr as $key => $val){
				$col = $key;
				if(isset($arr_fake_cols[$col])){
					$col = $arr_fake_cols[$col];
				}
				$value = $val[$i];
				$value = mysql_real_escape_string($value);
				$sql .= "`{$col}` = '" . $value . "', ";
			}
			$id = mysql_real_escape_string($id);
			$sql  = substr($sql, 0, strlen($sql) - 2);
			$sql .= " WHERE `{$colID}` = '{$id}'";			
			mysql_query($sql);	
		}
		if(!empty($page) && is_numeric($page)){	
			$query_string = preg_replace("/[&]?page=" . $page ."/", "", $query_string);
			$query_string = (!empty($query_string) && strpos($query_string, "&") !== 0)  ? "&" . $query_string : $query_string;			
			$page = intval($page);
			$url = $_SERVER["PHP_SELF"];
			$url .= "?page={$page}{$query_string}";
			redirect($url);			
		}		
	}	
}

function create_listBody($sql, $arr_column, $paging_value, $noresult = "Không có dữ liệu", $arr_link = array(), $head = "", $colspan = 999, $prev = "<", $next = ">"){
	$colID = $arr_column["__colID"];
	unset($arr_column["__colID"]);
	
	$rs = mysql_query($sql);
	$pgintf = "";
	$listbody = "";
	@$total_num = mysql_num_rows($rs);	
	if($total_num > 0){
		list($pgintf, $startnum) = createPaging($_SERVER["PHP_SELF"], strip_tags(@$_GET["page"]), $total_num, $paging_value, $_SERVER["QUERY_STRING"], $prev, $next);
		$sql .= " Limit $startnum, $paging_value";		
		$rs = mysql_query($sql);
		while($row = mysql_fetch_array($rs)){
			create_listBody_row($listbody, $arr_column, $row, $colID, $arr_link);			
		}		
		mysql_free_result($rs);
				
		if(!empty($head)){
			$listbody = $head . $listbody;
			$listbody .= "</tbody>\n";
			$listbody .= "</table>\n";
		}			
	}
	else{
		$listbody .= "<tr>\n";
		$listbody .= "<td colspan='{$colspan}'>".$noresult."</td>\n";
		$listbody .= "</tr>\n";
	}	
	return array($pgintf, $listbody, $total_num);
}

function create_listBody_row_parent(&$listbody, $row, &$parent){
	@$prev = $parent["prev"];
	$pID 	= $parent[0];
	$pName 	= $parent[1];
	if(empty($prev) || $prev != $row[$pID]){		
		$listbody .= "\t<tr>\n";			
		$parent["prev"] = $row[$pID];
		$view = $row[$pName];
		if(is_array($pName)){
			$extra = "colspan=\"".$parent["colspan"]."\"";
			if(isset($val["arr_style"])){
				foreach($val["arr_style"] as $k => $v){
					if(is_array($v)){
						$extra .= " {$k}=\"". $v[$value] ."\" ";
					}
					else{
						$extra .= " {$k}=\"". $v ."\" ";
					}							
				}
			}
			$listbody .= "\t\t<td{$extra}>".$view."</td>\n";
		}
		elseif(is_string($pName)){					
			$listbody .= "\t\t<td colspan=\"".$parent["colspan"]."\">".$row[$pName]."</td>\n";
		}		
		$listbody .= "\t</tr>\n";	
	}
}

function create_listBody_row_getStyle($val, $value = ""){
	$extra = "";
	if(isset($val["arr_style"])){
		foreach($val["arr_style"] as $k => $v){
			if(is_array($v)){
				$extra .= " {$k}=\"". $v[$value] ."\" ";
			}
			else{
				$extra .= " {$k}=\"". $v ."\" ";
			}							
		}
	}
	return $extra;
}

function create_listBody_row(&$listbody, $arr_column, $row, $colID, $arr_link = array()){
	$listbody .= "\t<input type=\"hidden\" name=\"id[]\" value=\"".$row[$colID]."\" />\n";
	$listbody .= "\t<tr>\n";
	foreach($arr_column as $key => $val){				
		if(is_array($val)){
			$value = $row[$key];
			$view = $value;
			if(isset($val["view"])){
				if(is_callable($val["view"])){
					$view = $val["view"]($value);
				}
				else if(is_array($val["view"]))
					$view = $val["view"][$value];				
			}
			else if(isset($val["edit"]) || in_array("edit", $val)){
				@$edit = $val["edit"];
				if(is_array($edit)){
					$extra = create_listBody_row_getStyle($edit);
					@$type = $edit["type"];	
					@$arr_val = $edit["arr_val"];					
					$name = $key;
					if(isset($edit["name"])){
						$name = $edit["name"];
					}
					switch($type){
						default:
						case "text":
							$view = "<input {$extra} type=\"text\" name=\"{$name}[]\" value=\"{$value}\" />";
							break;						
						case "select":
							if(is_array($arr_val)){
								$view = array_single_option_v2($arr_val, $value, $name . "[]", $extra);																
							}
							else{
								$where = empty($edit["where"]) ? 1 : $edit["where"];
								$value = mysql_real_escape_string($value);
								$where = "`{$key}` = '$value' OR ({$where})";
								$view = single_option_v2($value, "{$name}[]", $edit["table_name"], $where, $edit["colName"], $edit["colID"], @$edit["onchange"], "id=\"{$name}\" {$extra}");	
							}
							break;
					}
				}
				else{
					$view = "<input type=\"text\" name=\"{$key}[]\" value=\"{$value}\" />";
				}
			}			
			
			$extra = create_listBody_row_getStyle($val, $value);
			$listbody .= "\t\t<td{$extra}>".$view."</td>\n";
		}
		elseif(is_string($val)){					
			$listbody .= "\t\t<td>".$row[$val]."</td>\n";
		}
	}
	if(!empty($colID)){
		foreach($arr_link as $key => $val){
			$extra = create_listBody_row_getStyle($val, $value);
			$chkview = "";
			if(isset($val["checkbox"]) || in_array("checkbox", $val)){
				@$checkbox = $val["checkbox"];
				$name = "chk_del[]";
				if(is_array($checkbox)){					
					if(isset($checkbox["name"])){
						$name = $checkbox["name"];
					}
				}
				$chkview = "<input type=\"checkbox\" name=\"{$name}\" value=\"".$row[$colID]."\" />";
			}
			$td = "";
			if(isset($val["link"])){
				$name = $colID;
				if(isset($val["name"]))
					$name = $val["name"];
				$td .= "<a href=\"".$val["link"]."?".$name."=".$row[$colID]."\">".$val["view"]."</a>";
				if(!empty($chkview))
				$td .= " | ";
			}			
			$listbody .= "<td {$extra}>{$td}{$chkview}</td>\n";
		}
	}
	$listbody .= "\t</tr>\n";
}

function create_listBody_tree($sql, $arr_column, $paging_value, $noresult = "Không có dữ liệu", $arr_link = array(), $head = "", $prev = "<", $next = ">", $colspan = 999){
	$colID = $arr_column["__colID"];
	unset($arr_column["__colID"]);
	$parent = $arr_column["__parent"];	
	unset($arr_column["__parent"]);
	$parent["colspan"] = $colspan;
	
	$rs = mysql_query($sql);
	$pgintf = "";
	$listbody = "";
	@$total_num = mysql_num_rows($rs);	
	if($total_num > 0){
		list($pgintf, $startnum) = createPaging($_SERVER["PHP_SELF"], strip_tags(@$_GET["page"]), $total_num, $paging_value, $_SERVER["QUERY_STRING"], $prev, $next);
		$sql .= " Limit $startnum, $paging_value";		
		$rs = mysql_query($sql);
		while($row = mysql_fetch_array($rs)){
			create_listBody_row_parent($listbody, $row, $parent);
			create_listBody_row($listbody, $arr_column, $row, $colID, $arr_link);
		}
		mysql_free_result($rs);
		
		if(!empty($head)){
			$listbody = $head . $listbody;
			$listbody .= "</tbody>\n";
			$listbody .= "</table>\n";
		}			
	}
	else{
		$listbody .= "<tr>\n";
		$listbody .= "<td colspan='{$colspan}'>".$noresult."</td>\n";
		$listbody .= "</tr>\n";
	}	
	return array($pgintf, $listbody, $total_num);	
}

//----------------------------------------end createList----------------------------------------//

//SMTP Email
function smtp_email($pathinclude, $addto = array(), $mailsubject, $mailmessage, $addcc = array(), $contentType = ""){
	global $smtpusername;
	global $smtppassword;
	global $setfrom;
	
	if(!class_exists("EMail")){
		include_once $pathinclude."common/smtpEmail.php";
	}
	$mail = new EMail;
	$mail->Username = $smtpusername;
	$mail->Password = $smtppassword;
	
	if(!empty($setfrom)){
		foreach($setfrom as $fromName => $fromEmail){
			$mail->SetFrom($fromEmail, $fromName);
		}
	}
	if(!empty($addto)){
		foreach($addto as $recipientName => $recipientEmail){
			$mail->AddTo($recipientEmail, $recipientName);
		}
	}
	$mail->Subject = $mailsubject;
	$mail->Message = $mailmessage;
	if(!empty($addcc)){
		foreach($addcc as $ccName => $ccEmail){
			$mail->AddCc($ccEmail, $ccName);
		}
	}
	if(!empty($contentType)){
		$mail->ContentType = $contentType;
	}
	
	return $success = $mail->Send();
}
//smtp_email("../", $addto, $mailsubject, $mailmessage, $addcc, "");

//----------------------------------------end Captcha----------------------------------------//
function get_captcha_v2($type=1,$numletters=5,$fontsize=17, $text = ""){
	$dir = realpath(dirname(__FILE__));
	$font = $dir . "/captcha/font-bg/";	
	$dir  = $dir . "/captcha/images/";

	// delete all captcha images at 12 and 3 oclock if more than 100 are found
	$dt=date('g');
	if(($dt==15)||($dt=='15')) capya_cleanup($dir);
	else if(($dt==4)||($dt=='4')) capya_cleanup($dir);
	/**/
	if(empty($text))	
		$capya_string = capya_string($numletters);				// the letters and numbers displayed on captcha
	else
		$capya_string = $text;
	$capya_bgfile = $font . 'n.png';							// the background image for the captcha
	$capya_filename='captcha-'.rand(1111,999999).'.jpg';		// the filename of finished captcha
	$capya_file=$dir.$capya_filename;					// the full path to finished captcha
	$rgb[0]=array(204,0,0);
	$rgb[1]=array(34,136,0);
	$rgb[2]=array(51,102,204);
	$rgb[3]=array(141,214,210);
	$rgb[4]=array(214,141,205);
	$rgb[5]=array(100,138,204);

	// create image from background image
	$image=imagecreatefrompng($capya_bgfile);
	
	// store the md5 of the captcha string
	//$_SESSION['askapache_captcha'] = md5($capya_string);
	if(!isset($_SESSION))
		session_start();
	$_SESSION['chk_captcha'] = strtolower($capya_string);
	
	//set cookie use for javascript
	//setcookie ("ca", strtolower($capya_string), -2); 
	//setcookie ("ca", strtolower($capya_string), time()+3600*24*(1));

	// add chars to captcha image
	$g=$fontsize;
	for($i=0; $i<$numletters; $i++){
		$L[]=substr($capya_string,$i,1);    // each char from string into individual variable
		$A[]=rand(-20, 20);			// random angle for each char
		$F[]=$font.rand(1, 10).".ttf";  // random font for each char
		$C[]=rand(0, 5);			// random color for each char
		$T[]=imagecolorallocate($image,$rgb[$C[$i]][0],$rgb[$C[$i]][1],$rgb[$C[$i]][2]);	// allocate colors for chars
		imagettftext($image, $fontsize, $A[$i], $g, $fontsize+15, $T[$i], $F[$i], $L[$i]);	// write chars to image
		$g+=$fontsize+10;
	}

	// save jpeg image to public web folder
	return $image;
}

function get_captcha($homepage = "", $type=1,$numletters=5,$fontsize=17){
	$dir = realpath(dirname(__FILE__));
	$url  = $homepage . "common/captcha/images/";
	$font = $dir . "/captcha/font-bg/";	
	$dir  = $dir . "/captcha/images/";

	// delete all captcha images at 12 and 3 oclock if more than 100 are found
	$dt=date('g');
	if(($dt==15)||($dt=='15')) capya_cleanup($dir);
	else if(($dt==4)||($dt=='4')) capya_cleanup($dir);
	/**/
	$capya_string = capya_string($numletters);				// the letters and numbers displayed on captcha
	$capya_bgfile = $font . 'n.png';							// the background image for the captcha
	$capya_filename='captcha-'.rand(1111,999999).'.jpg';		// the filename of finished captcha
	$capya_file=$dir.$capya_filename;					// the full path to finished captcha
	$capya_uri=$url.$capya_filename;					// the public web address to finished captcha
	$rgb[0]=array(204,0,0);
	$rgb[1]=array(34,136,0);
	$rgb[2]=array(51,102,204);
	$rgb[3]=array(141,214,210);
	$rgb[4]=array(214,141,205);
	$rgb[5]=array(100,138,204);

	// create image from background image
	$image=imagecreatefrompng($capya_bgfile);
	
	// store the md5 of the captcha string
	//$_SESSION['askapache_captcha'] = md5($capya_string);
	if(!isset($_SESSION))
		session_start();
	$_SESSION['chk_captcha'] = strtolower($capya_string);
	
	//set cookie use for javascript
	//setcookie ("ca", strtolower($capya_string), -2); 
	//setcookie ("ca", strtolower($capya_string), time()+3600*24*(1));

	// add chars to captcha image
	$g=$fontsize;
	for($i=0; $i<$numletters; $i++){
		$L[]=substr($capya_string,$i,1);    // each char from string into individual variable
		$A[]=rand(-20, 20);			// random angle for each char
		$F[]=$font.rand(1, 10).".ttf";  // random font for each char
		$C[]=rand(0, 5);			// random color for each char
		$T[]=imagecolorallocate($image,$rgb[$C[$i]][0],$rgb[$C[$i]][1],$rgb[$C[$i]][2]);	// allocate colors for chars
		imagettftext($image, $fontsize, $A[$i], $g, $fontsize+15, $T[$i], $F[$i], $L[$i]);	// write chars to image
		$g+=$fontsize+10;
	}

	// save jpeg image to public web folder
	imagejpeg($image, $capya_file);
			
	// destroy image
	imagedestroy($image);		
	return $url . $capya_filename;
}

function capya_cleanup($dir = "capcha/"){
	$files=glob($dir . "*.jpg");
	if(sizeof($files)>100){
		foreach ($files as $filename) {
			//echo "$filename size " . filesize($filename) . "\n";
			unlink($filename);				
		}
	}
}

function capya_string($len){
	$str='';
	for($i=1; $i<=$len; $i++) {
		$ord=rand(48, 122);
		if((($ord >= 48) && ($ord <= 57)) || (($ord >= 97) && ($ord<= 122)) || (($ord >= 65) && ($ord<= 90))) $str.=chr($ord);
		else $str .= capya_string(1);
	}
	return $str;
}
//----------------------------------------end Captcha----------------------------------------//

//----------------------------------------Functions use for array language----------------------------------------//

function lang_key($code, $key)
{
	return $key . "_" . $code;			
}

function lang_empty_err($lang_key)
{
	return $lang_key . "_empty";
}

function lang_empty_text($err_lang, $lang_key, $title, $err_empty = "")
{
	$err_text = "";
	if(in_array($lang_key, $err_lang))
		$err_text = "<br /><span class=\"required\">" . $err_empty . " " . strtolower($title) . "." ."</span>";	
	return $err_text;
}

function lang_ckeditor($language, $arr_fields, $arr_lang, $homepage)
{
	$curr_dir = realpath(dirname(__FILE__)) . "/";
	include_once($curr_dir . "ckeditor/ckeditor.php");	
	include_once($curr_dir . "ckfinder/ckfinder.php");
	$ckeditor = new CKEditor();
	$ckeditor->basePath = $homepage . "common/ckeditor/";	
	CKFinder::SetupCKEditor($ckeditor, $homepage . "common/ckfinder/");
	$la = strtolower($language);	
	foreach($arr_fields as $key => $value)
	{
		@$type = $value["type"];
		foreach($arr_lang as $code => $lang){
			$lang_key = lang_key($code, $key);
			switch($type){
				case "ckeditor":
					$ckeditor->replace($lang_key, array("language" => $la));	
					break;
				default:
					break;
			}
		}
	}
}

function lang_addData($table, $where, $arr_fields, $arr_lang, $colLang = "lan")
{
	$sql = "select * from `{$table}` where {$where}";
	$rs = mysql_query($sql);
	if(@mysql_num_rows($rs) > 0){
		while($row = mysql_fetch_array($rs)){
			foreach($arr_fields as $key => $value){
				$code = $row[$colLang];
				$val = $row[$key];
				$lang_key = lang_key($code, $key);
				$_SESSION[$lang_key] = $val;
			}			
		}
	}
}

function lang_createFields($arr_lang, $arr_fields, $arr_lang_chk_empty = array(), $err_empty = "", $arr_err = array())
{
	$fields = "";
	$required = "<span class=\"required\">※</span>";	
	$arr_ck = array();
	$err_lang = empty($_SESSION["err_lang"]) ? array() : $_SESSION["err_lang"];
	unset($_SESSION["err_lang"]);
	foreach($arr_fields as $key => $value){
		@$type = $value["type"];
		@$title = $value["title"];
		$attr = "";
		if(array_key_exists("arr_attr", $value)){
			foreach($value["arr_attr"] as $k => $v){
				$attr .= "$k=\"{$v}\"";				
			}			
		}
		
		foreach($arr_lang as $code => $lang){			
			$lang_key = lang_key($code, $key);
			@$text = $_SESSION[$lang_key];
			unset($_SESSION[$lang_key]);
			$text = htmlentities($text, ENT_QUOTES, "UTF-8");
			
			$req = "";
			@$err_text = $arr_err[$lang_key];
			foreach($arr_lang_chk_empty	as $c){
				if(@$value["required"] === false){}
				else{
					if($c == $code || @in_array($code, $value["required"])){
						$err_text .= lang_empty_text($err_lang, $lang_key, $title, $err_empty);
						$req = $required;
					}
				}
			}
			
			$note = "";
			if(!empty($value["note"]))
				$note = "<span class=\"example\">".$value["note"]."</span>";
			$fields .= "\t<tr>\n";
			$fields .= "\t\t<th>" . $title . " ($lang)" . "{$req}</th>\n";
			switch($type){
				default:
				case "text":				
					$fields .= "\t\t<td><input {$attr} type=\"text\" name=\"{$lang_key}\" id=\"{$lang_key}\" value=\"{$text}\" />" . $note . $err_text . "</td>";
					break;
				case "ckeditor":
				case "textarea":
					$fields .= "\t\t<td><textarea {$attr} name=\"{$lang_key}\" id=\"{$lang_key}\">{$text}</textarea>" . $note . $err_text . "</td>";				
					break;			
			}	
			$fields .= "\t</tr>\n";	
		}		
	}
	return $fields;	
}

function lang_checkErr_empty($text, $lang_key)
{
	$em_k = lang_empty_err($lang_key);
	if(empty($text))
		$_SESSION[$em_k] = true;
}

function lang_createViews($arr_lang, $arr_fields, $arr_lang_chk_empty = array(), $for_views = false)
{
	$views = "";
	$arr_ck = array();
	$err_lang = array();
	foreach($arr_fields as $key => $value){
		@$type = $value["type"];
		@$title = $value["title"];
		
		foreach($arr_lang as $code => $lang){			
			$lang_key = lang_key($code, $key);
			
			if($for_views){
				@$text = $_SESSION[$lang_key];
				unset($_SESSION[$lang_key]);
			}
			else{
				@$text = $_POST[$lang_key];
				@$_SESSION[$lang_key] = $text;
			}

			foreach($arr_lang_chk_empty	as $c){
				if(@$value["required"] === false){}
				else{
					if($c == $code || @in_array($code, $value["required"])){
						if(empty($text))
							$err_lang[] = $lang_key;
					}
				}
			}
						
			$views .= "\t<tr>\n";
			$views .= "\t\t<th>" . $title . " ($lang)" . "</th>\n";
			switch($type){
				default:
				case "text":				
					$views .= "\t\t<td>{$text}</td>";
					break;
				case "textarea":
					$text = nl2br($text);
				case "ckeditor":								
					$views .= "\t\t<td>{$text}</td>";				
					break;			
			}	
			$views .= "\t</tr>\n";	
		}		
	}

	if(!$for_views)
		$_SESSION["err_lang"] = $err_lang;
	return $views;
}

function lang_checkErrEmpty($arr_lang, $arr_fields, $arr_lang_chk_empty = array())
{
	$err_lang = array();
	foreach($arr_fields as $key => $value){		
		foreach($arr_lang as $code => $lang){			
			$lang_key = lang_key($code, $key);
			@$text = $_SESSION[$lang_key];
			foreach($arr_lang_chk_empty as $c){
				if(@$value["required"] === false){}
				else{
					if($c == $code || @in_array($code, $value["required"])){
						if(empty($text))
							$err_lang[] = $lang_key;
					}
				}
			}
		}		
	}
	$_SESSION["err_lang"] = $err_lang;
}


function lang_accesstData($table ,$arr_lang, $arr_fields, $def = array(), $arr_lang_chk_empty = array(), $colID = "", $beginID = 0, $colLang = "lan")
{		
	if(empty($def))
		return;
	
	foreach($def as $k => $v){
		$pid = $k;
		$pval = $v;
		break;		
	}
	$pval = mysql_real_escape_string($pval);
	
	$sql = "";
	$sql_insert_def_key = "";
	$sql_insert_def_val = "";
	$sql_update_def_upd = "";
	foreach($def as $k => $v){
		$sql_insert_def_key .= "`$k`, ";
		$sql_insert_def_val .= "'$v', ";
		$sql_update_def_upd .= "`$k` = '$v', ";
	}	
	foreach($arr_lang as $code => $lang){
		$id_val = single_select($table, $colID, "`$pid` = '$pval' AND `$colLang` = '$code'");
		$sql_insert_key = "INSERT INTO {$table}(" . $sql_insert_def_key;
		$sql_insert_val = "VALUES(" . $sql_insert_def_val;
		$sql_update_upd = "UPDATE {$table} SET " . $sql_update_def_upd;
		foreach($arr_fields as $key => $value){
			$lang_key = lang_key($code, $key);
			@$text = $_SESSION[$lang_key];
			unset($_SESSION[$lang_key]);
			$text = mysql_real_escape_string($text);
			
			$sql_insert_key .= "`$key`, ";
			$sql_insert_val .= "'$text', ";
			$sql_update_upd .= "`$key` = '$text', ";		
		}
		if(empty($id_val)){
			$sql_insert_key .= "`$colLang`, ";
			$sql_insert_val .= "'$code', ";
			$sql_insert_key .= "`$colID`)";
			if($beginID != 0){
				$id_val = generate_id($table, $colID, $beginID);
				$sql_insert_val .= "'$id_val')";
			}			
			else{
				$sql_insert_val .= "NULL);";
			}
			$sql = $sql_insert_key . $sql_insert_val;
		}
		else{
			$sql_update_upd = substr($sql_update_upd, 0, strlen($sql_update_upd) - 2);
			$sql_update_upd .= " WHERE `$colID` = '$id_val';";
			$sql = $sql_update_upd;
		}
		mysql_query($sql);
	}
}

function POST_To_SESSION(){
	foreach($_POST as $key => $val){
		$_SESSION[$key] = $val;
	}
}

function unsetPOSTSESSION()
{
	foreach($_POST as $key => $val){
		unset($_SESSION[$key]);
	}	
}

//----------------------------------------end Functions use for array language----------------------------------------//

function substr_unicode($str, $s, $l = null) {
    return join("", array_slice(
        @preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
}


//----------------------------------------Functions use for cURL----------------------------------------//

function cURL($url, $header=NULL, $cookie=NULL, $p=NULL)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HEADER, $header);
	curl_setopt($ch, CURLOPT_NOBODY, $header);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	if ($p) {
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $p);
	}
	$result = curl_exec($ch);
	if ($result) {
		return $result;
	} else {
		return curl_error($ch);
	}
	curl_close($ch);
}	

function createYoutubeDataDetail($html){
	$arr = array();
	preg_match('/<a class="feed-video-title(.*)>(.*)<\/a>/s', $html, $m2);
	$title = trim($m2[2]);
	preg_match('/href="(.*)data-sessionlink/s', $m2[1], $m3);
	$link = trim($m3[1]);
	$link = str_replace("\"", "", $link);
	$link = str_replace("/", "http://www.youtube.com/", $link);
	$ind = strpos($link, "&");
	if($ind !== false){
		$code = substr($link, 0, $ind);
		preg_match('/watch\?v=(.*)/', $code, $m2);
	}
	else
		preg_match('/watch\?v=(.*)/', $link, $m2);
	$code = $m2[1];
	preg_match('/watch\?v=(.*)&/', $link, $m2);
	$code = $m2[1];
	preg_match('/<span class="view-count">(.*)<\/span>/s', $html, $m2);
	$views = trim($m2[1]);
	preg_match('/<div class="description"(.*)<p>(.*)<\/p>(.*)<\/div>/s', $html, $m2);
	@$description = trim($m2[2]);
	preg_match('/data-thumb="(.*)" width=\"185\"/', $html, $m2);	
	$img = $m2[1];
	$arr = array("title" => $title, "link" => $link, "views" => $views, "description" => $description, "img" => $img, "code" => $code);
	return $arr;
}

function createYoutubeData($link){
	//$link = "http://www.youtube.com/user/baokyhamnghihue?feature=results_main";
	//$data = cURL($link);
	$data = file_get_contents($link);
	preg_match_all('/<div class="feed-item-container(.*)<div class="feed-item-dismissal-notices">/sU', $data, $m);	
	$arr = array();
	if(count($m) > 1){
		if(count($m[1]) > 0){
			foreach($m[1] as $html){
				$arr[] = createYoutubeDataDetail($html);
			}
		}
	}
	return $arr;
}
	
//----------------------------------------end Functions use for cURL----------------------------------------//

function render($file, $data){
	extract($data);
	ob_start();
	include($file);
	$data = ob_get_contents();
	ob_end_clean();
	return $data;
}

function myCrypt($user, $pass)
{
	return $pass;
	//return crypt($user + $pass);
}

function stripUnicode($str) {
	$unicode = array(
		'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ|A|À|Á|Ả|Ạ|Ã|Ă|Ằ|Ắ|Ẳ|Ặ|Ẵ|Â|Ầ|Ấ|Ẩ|Ậ|Ẫ',
		'd'=>'đ|D|Đ',
		'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|E|È|É|Ẻ|Ẹ|Ẽ|Ê|Ề|Ế|Ể|Ệ|Ễ',
		'i'=>'í|ì|ỉ|ĩ|ị|I|Ì|Í|Ỉ|Ị|Ĩ',
		'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ|O|Ò|Ó|Ỏ|Ọ|Õ|Ô|Ồ|Ố|Ổ|Ộ|Ỗ|Ơ|Ờ|Ớ|Ở|Ợ|Ỡ',
		'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|U|Ù|Ú|Ủ|Ụ|Ũ|Ư|Ừ|Ứ|Ử|Ự|Ữ',
		'y'=>'ý|ỳ|ỷ|ỹ|ỵ|Y|Ỳ|Ý|Ỷ|Ỵ|Ỹ',
	);
	$str = preg_replace('/[ ]+/', ' ', $str);
	$str = str_replace(' ', '-', str_replace('&*#39;','',$str));
	foreach($unicode as $nonUnicode => $uni) $str = preg_replace("/($uni)/i",$nonUnicode,$str);
	$str = strtolower($str);
	$str = preg_replace("/[^a-z\-]/", "", $str);
	$str = preg_replace("/[^a-z]$/", "", $str);
	return $str;
	/*
	String[] arUni = { 
"a", "à", "á", "ả", "ạ", "ã", "ă", "ằ", "ắ", "ẳ",
"ặ", "ẵ", "â", "ầ", "ấ", "ẩ", "ậ", "ẫ", "A", "À", "Á", "Ả",
"Ạ", "Ã", "Ă", "Ằ", "Ắ", "Ẳ", "Ặ", "Ẵ", "Â", "Ầ", "Ấ", "Ẩ",
"Ậ", "Ẫ", "o", "ò", "ó", "ỏ", "ọ", "õ", "ô", "ồ", "ố", "ổ",
"ộ", "ỗ", "ơ", "ờ", "ớ", "ở", "ợ", "ỡ", "O", "Ò", "Ó", "Ỏ",
"Ọ", "Õ", "Ô", "Ồ", "Ố", "Ổ", "Ộ", "Ỗ", "Ơ", "Ờ", "Ớ", "Ở",
"Ợ", "Ỡ", "e", "è", "é", "ẻ", "ẹ", "ẽ", "ê", "ề", "ế", "ể",
"ệ", "ễ", "E", "È", "É", "Ẻ", "Ẹ", "Ẽ", "Ê", "Ề", "Ế", "Ể",
"Ệ", "Ễ", "u", "ù", "ú", "ủ", "ụ", "ũ", "ư", "ừ", "ứ", "ử",
"ự", "ữ", "U", "Ù", "Ú", "Ủ", "Ụ", "Ũ", "Ư", "Ừ", "Ứ", "Ử",
"Ự", "Ữ", "i", "ì", "í", "ỉ", "ị", "ĩ", "I", "Ì", "Í", "Ỉ",
"Ị", "Ĩ", "đ", "Đ", "y", "ỳ", "ý", "ỷ", "ỵ", "ỹ", "Y", "Ỳ",
"Ý", "Ỷ", "Ỵ", "Ỹ" };
/**/
}


function add_before_ext($text, $str){
	$ext = pathinfo($str, PATHINFO_EXTENSION);
	$filename = pathinfo($str, PATHINFO_FILENAME );
	return $filename . "_{$text}." . $ext;
}

?>